Static variable not being shared across instances of an Actor class

An embarrassingly basic question here, I’m using a static variable as a counter in my class with the expectation that it will be shared among all instances of that class but each class seems to store it’s own version of the variable like a non-static member.

The header file has a variable to store a uniqueId and also a static counter like so:

UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = AerialNavigation)
	int32 volumeId;


	static int32 volumeIdCounter;

and in the implementation I’m incrementing the counter in the constructor and assigning the value to the id to create a very simple counter:


	volumeId = MyClass::volumeIdCounter;

So when I run the code the “volumeId” assigned to every instance remains “1”, i.e each class seems to be maintaining its own version of the static variable.

Any idea what I’m missing? Not sure if my C++ has atrophied so badly from lack of use that I’ve started goofing up even static variable usage :slight_smile:

Edit: I did read the posts about using the global singleton class for sharing data in global scope but that seemed like an overkill for what I’m doing here, especially as this is prototype code that I’m just blocking out for testing.

I think thats because constructor is used only for Archetype, once. Im not sure though.

Try to override AActor::OnConstruction maybe?

UPD: internally constructor is not actually called once, and static variable still incremented, but UPROPERTY seems use default values only from 1st constuctor call, and they overrided with default values after next constructor calls.

The problem is because you have a uproperty for the VolumeID. In the constructor you will be assigning the instances a new value and incrementing the static, however, when the class default object (CDO) properties are copied in to the instance as part of the initialization process, it will write over it and make it the same value as the CDO.

If you were to do the assignment and increment in PostInitProperties I think you will have better luck.