Search code examples
c++staticunreal-engine4static-variables

Initializing static variables in ue4 c++


I have a actor class ANodeBase. Each node must have a unique id. To realize that, i create static variable id_counter.

Code:

//ANodeBase.h
static int id_counter;
//ANodeBase.cpp
#include "NodeBase.h"

int ANodeBase::id_counter = 0;

ANodeBase::ANodeBase()
{
    PrimaryActorTick.bCanEverTick = false;
    id = id_counter;
    id_counter++;//the only change to a variable in the project
}

Problem is that id_counter wasn't initialized, more precisely, it is initialized by 13, even if I restart ue4, even when I add some code and recompile project. When I create other actors, they increase be 1.

If it important, object directly created in the engine is BP_NodePC : NodePC : NodeBase : Actor

Can someone explain why does it happen or suggest an alternative count.

EDIT: For some unknown reason, unreal create 12 objects before launch. Don't know how fix that and why it happening


Solution

  • As we found out, unreal creates CDO (class default object), which call constructor. Accordingly, I transfer my code to BeginPlay() and now it's work.