Currently, I’m trying to create a 2D vector array of AGasVolume actors (a class which I created).
My code compiles fine, but I keep getting a crash on the follow code:
for(int x = xStart; x <= xEnd; x += 100)
{
std::vector<AGasVolume *> newColumn;
gasVolumes.at(x) = newColumn;
for(int y = yStart; y <= yEnd; y += 100)
{
AGasVolume *gv = GetWorld()->SpawnActor<AGasVolume>(AGasVolume::StaticClass(), SpawnInfo);
if (gv == nullptr) {
UE_LOG(LogTemp, Warning, TEXT("Wow, we have a nullptr!"));
}else {
gasVolumes[x][y] = gv; // HERE IS THE CRASH
}
}
}
[UE_LOG(LogTemp, Warning, TEXT("Value of 100, 100: %f"), gasVolumes[100][100]->Oxygen());][1]
I initially tried doing a 2D array, but that was giving me a crash as well, so I switched to vector and that didn’t help.
Try using TArrays instead of vectors ie TArray …
though that wouldnt give you 2 dimensions.
For that you could use a TMap … or something similar.
My advice to you would be spend some time reading the documentation for TArray and TMap and the sample code as well as the sections regarding spawning actors, and use as much from within the engine api as possible rather than trying to mix engine objects with std lib.
You did not set the sizes of your vectors. So when you assign the value at [x][y], that element of the array is not allocated.
You can fix this by setting the vector sizes:
// set number of rows
gasVolumes.resize(count_rows)
for(int r = 0; x < count_rows; r++)
{
// for each row, allocate the whole column
gasVolumes[r].resize(count_cols);
// fill column with actors with direct indexing
for(int c = 0; c < count_cols; c++)
{
gasVolumes[r][c] = spawn_new_actor();
}
}
or alternatively with push_back to add elements one by one:
// set number of rows
gasVolumes.resize(count_rows)
for(int r = 0; x < count_rows; r++)
{
// fill column with actors one by one
for(int c = 0; c < count_cols; c++)
{
gasVolumes[r].push_back(spawn_new_actor());
}
}
I see you also increment the index by 100: x += 100. If you use std::vector, the indices should be consecutive integers - gaps between indices them will waste space.
If you want to store data on sparse indices (0, 100, 200, …), then you should use a map ( std::map, std::unordered_map or TMap) instead.