Static TArray


I am trying to create static TArray for holding spawned actors.

Here is my code
//For removing old roads.
static TArray<ARoadSpawn*> spawnedRoads;


//If length of spawned road exceeds maximum spawned road remove first element of array
if (ARoadSpawn::spawnedRoads.Num() > maximumRoadNumber) {
	ARoadSpawn* firstElement = ARoadSpawn::spawnedRoads[0];

However this code gives me a linker error. I am creating and using this array already in RoadSpawn class.

What could be the reason of that error?

Error RoadSpawn.cpp.obj : error LNK2001: unresolved external symbol "public: static class TArray<class ARoadSpawn *,class FDefaultAllocator> ARoadSpawn::spawnedRoads" (?spawnedRoads@ARoadSpawn@@2V?$TArray@PEAVARoadSpawn@@VFDefaultAllocator@@@@A)

It would be actually more helpful if you would include definition of array in class itself. I guess it should look like this:

UCLASS() class ARoadSpawn : public AActor{
    static TArray<AActor*> spawnedRoads;

and you can call it exactly the same as you do it in your code.

1 Like

I guess it can be a problem because you used a pointer to ARoadSpawn instead to AActor, but I am not really sure. You can try write declaration
class ARoadSpawn; before actual class definition, but it shouldn’t be even an issue.

This has been answered a couple of times. I think your problem may be the same as e.g. this question:

tl;dr: in c++ it’s not enough to declare a static variable in the .h file, you also need to define it in the .cpp:


static TArray<AActor*> spawnedRoads;


TArray<AActor*> RoadSpawn::spawnedRoads;
1 Like