Why is everything rotating randomly when spawning?

I’m trying to build a simple racing game with an in-game track editor.
It works by using a “block” class that has an index associated with it.
When saving a track in the editor it finds all actors that have a parent class of block and creating an array of this struct out of their indices, locations, and rotation along the Z axis, which is saves to a file:

struct FBlockData {

public:

int index;

FVector location;

float yaw;

};

After loading the array it goes through this loop to spawn all of the blocks:

for (int32 i = 0; i <
blockDataArray.Num(); i++) {

FRotator rotation;

rotation.Yaw = blockDataArray[i].yaw;

world->SpawnActor(Blocks[blockDataArray[i].index], blockDataArray[i].location, rotation);

}

This system has worked for a few weeks without any problems, but it suddenly started rotating every block a random amount (the same for each block) around the Y axis when spawning. The bug started when I saved this testing track (all tracks had the problem). Re-saving the track seemed to have fixed it for this track, but it didn’t work for any of the others. In the track editor spawning new blocks to add to the track spawned with the correct rotation, however after saving and re-loading for all but the one track they would rotate randomly.

Specifically adding in “rotation.Roll = 0;” and “rotation.Pitch = 0;” in the spawn loop seems to have fixed it for all of the tracks, however as far as I know they should both default to 0, so I’m not sure if this bug will show up again, and I’d like to know why it happened in the first place.

I can show more code or a video of the bug if needed.

Anyone have any insight as to why this happened?

Thanks! I guess I don’t understand initialization well, as I thought the float would default to 0. I wonder why it’s always ended up as 0 before.

Probably happenstance; many memory allocation methods clear the new block to zero when called. It could be that in most cases you were getting new memory, but that in recent iterations the memory was used elsewhere before being repurposed for your new FRotators.

Uninitialized variables are never reliable. If you don’t know that a class initializes its internals, treat it as if it’s populated with garbage, because it probably is.


Please mark this as closed/resolved for tracking.

According to the FRotator docs, the default constructor does no initialization:

FRotator | Unreal Engine Documentation

So the floats within your new FRotator have not been initialized to 0, and thus could be anything.

Probably better to create the variable outside your loop, initialize it with the static ZeroRotator, and then only update the Yaw value in the body of the loop.

FRotator rotation = FRotator::ZeroRotator;
for (int32 i = 0; i < blockDataArray.Num(); i++)
{
    rotation.Yaw = blockDataArray[i].yaw;
    world->SpawnActor(Blocks[blockDataArray[i].name], blockDataArray[i].location, rotation);
}