I tried converting my blueprint code to c++ and I stumbled uppon this error, the error given is Array index out of bounds. I get this error by running this code:
TArray<int32> AVoxelActor::CalculateNoise_Implementation()
{
TArray<int32> Noise;
for (int32 y = 0; y < ChunkLineElements - 1; y++)
{
for (int32 x = 0; x < ChunkLineElements - 1; x++)
{
float noiseF = USimplexNoiseBPLibrary::SimplexNoise2D((x + (ChunkXIndex * ChunkLineElements)) * xMult, (y + (ChunkYIndex * ChunkLineElements)) * yMult) * Weight;
Noise.Add(FMath::FloorToInt(noiseF));
}
}
return Noise;
}
I have a function called GenerateChuncks which gets called on beginplay.
void AVoxelActor::GenerateChunks()
{
ChunkFields.SetNumUninitialized(ChunkTotalElements);
TArray<int32> noise = CalculateNoise(); //HERE
for (int x = 0; x < ChunkLineElements; x++)
{
for (int y = 0; y < ChunkLineElements; y++)
{
for (int z = 0; z < ChunkZElements; z++)
{
int32 index = x + (y * ChunkLineElements) + (z * ChunkLineElementsP2);
ChunkFields[index] = (z < 30 + noise[x + y * ChunkLineElements]) ? 1 : 0;
}
}
}
}
TArray<int32> AVoxelActor::CalculateNoise_Implementation()
{
TArray<int32> Noise;
for (int32 y = 0; y < ChunkLineElements - 1; y++)
{
for (int32 x = 0; x < ChunkLineElements - 1; x++)
{
float noiseF = USimplexNoiseBPLibrary::SimplexNoise2D((x + (ChunkXIndex * ChunkLineElements)) * xMult, (y + (ChunkYIndex * ChunkLineElements)) * yMult) * Weight;
Noise.Add(FMath::FloorToInt(noiseF)); //And here is the part which makes it all crash
}
}
return Noise;
}
It’s more then likely crashing at ChunkFields[index] = (z < 30 + noise[x + y * ChunkLineElements]) ? 1 : 0; as it’s the only place I can see in your code where you access the array. You would likely be getting a different error if it was crashing when adding, but TArray will auto grow as you add more elements to it so you shouldn’t get errors when adding.
My guess is that you forgot to add the loop for the Z index in your CalculateNoise(); function.
So I found the bug, It had to do with the for loop and that I used:
ChunkLineElements - 1.
Its weird because this is how I did it in blueprint. And I converted it to code and now it works but than I don’t need to do -1.
Thanks everyone for your help and your time. I still don’t know why this would be different but thanks everyone.