Static TArray

Hello,

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

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

.cpp

//If length of spawned road exceeds maximum spawned road remove first element of array
if (ARoadSpawn::spawnedRoads.Num() > maximumRoadNumber) {
	ARoadSpawn* firstElement = ARoadSpawn::spawnedRoads[0];
	firstElement->Destroy();
	ARoadSpawn::spawnedRoads.RemoveAt(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{
    GENERATED_BODY()
    //...
    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:

RoadSpawn.h:

static TArray<AActor*> spawnedRoads;

RoadSpawn.cpp:

TArray<AActor*> RoadSpawn::spawnedRoads;