[C++] TArray is empty if it isn't a UPROPERTY

I have a TArray of an FStruct.

The number of elements in this array is determined by a UPROPERTY value so I can change it easily in the editor if need be. The array is grown/shrunk within OnConstruction(). Furthermore, for the purposes of debugging this error, I added another UPROPERTY variable which, at the end of OnConstruction(), is MyArray.Num().

I print on BeginPlay what that TArray number is. When my TArray is preceded with the UPROPERTY line, the TArray.Num() value is correct - that is, it is what I set it to, and it equals the “OnConstruction Number”.

However, when the TArray is not a UPROPERTY, the TArray.Num() value becomes 0 on BeginPlay - however, the “OnConstruction Number” indicates that I had more than that before BeginPlay.

Hey -

Also, are you populating the array in OnConstruction as well or doing so through the editor? If you are populating the array through the editor before removing the UPROPERTY macro, then this would be expected since after the macro is removed the array is no longer visible to the editor so it wouldn’t know what the size is supposed to be. Additionally, TArrays are dynamic by default. Rather than having its size set manually, their size will grow/shrink as elements are populated (with .Add(Value)) or removed. Can you provide the code you’re using to change the size of the array in OnConstruction()?

The elements are added in OnConstruction, as follows:

void AMathMaster::OnConstruction(const FTransform& Transform)
{
	Super::OnConstruction(Transform);

	if (DataNum > DataStructs.Num())
	{
		DataStructs.AddDefaulted(DataNum - DataStructs.Num());
	}
	else if (DataNum < DataStructs.Num())
	{
		DataStructs.RemoveAt(DataNum, DataStructs.Num() - DataNum);
	}

	DataStructsCount = DataStructs.Num();
}

with DataNum being the inputted number of structs to create, DataStructs being the TArray, and DataStructsCount being the outputted “OnConstruction Number” I referred to so I can see that it actually did add the number of specified elements.

After some experimentation it appears what is happening is a state change on the actor where OnConstruction isn’t called. When the actor enters play and the array is not set as a UPROPERTY, the array is as a default value which is zero (empty). This can also be seen by removing the UPROPERTY from DataStructsCount. It will show as set in the editor but resets to the default value for int32 on play which is zero.

Both of these instances apply to instances that are placed directly into the viewport. Since OnConstruction is called for updates in the editor as well as spawned actors, if you create a blueprint and change the default values there then use the Spawn Actor node/call, this will run OnConstruction and your DataStructs.Num will equal DataNum as expected.

Cheers

1 Like