How to use timers from classes which are not placed in the level

Hi,

I am working on UE5.1.

Please look at the following class pseudocode

Class A :  public AActor {
public:
    void CooldownExpirationCallback() { // print something }
    void func_to_use_timers() { 
        GetWorld()->GetTimerManager().SetTimer(CooldownTimerHandle, this, &A ::CooldownExpirationCallback, 5, false, -1);
    }
    FTimerHandle CooldownTimerHandle;
};

If I put this actor on the level in IDE, timers are working without any problem.

But if I create a separate class like below:

Class B :  public AActor {
public:
    void :BeginPlay() { 
        myA= NewObject<A>();
    }
    void useA() { A->func_to_use_timers(); }
    A* myA;
};

And place only B to the level, and call B.useA(), timer won’t work.

I believe I understand the reason: GetWorld() function returns NULL in this case (because B is in the level, not A). Thus, according to UE documentation I have another option, get Timer Manager not through Actor’s GetWorld() method, but through GameInstance().

So, I tried GetGameInstance()->... in order to access TimerManager. But even a pure call to GetGameInstance() (without dereferencing it) crashes the IDE.

So, my question is how to use a timer in such situations (where class owning the method to call GetWorld()->GetTimerManager().SetTimer(…) is not placed on the level).

I would appreciate your help.

Maybe what you are looking for is to Extend the original class?

Thanks for your reply. Actually I don’t want to extend the original class. Class A is a representation of an ability class. There will be many child classes of this class. On the other hand, Class B represents the playable character class. The reason why Class A is an actor, is because I tried with UObject, and timer’s don’t seem to work there. Since UObject cannot be placed on level, getWorld returns NULL.

I need to understand what should I do so that timers get to work on internal objects that are not on the level.

You cannot.
If an object is not in game it has no time or functions for you to call.

I get it. Thank you.

The workaround that I did was to pass AAactor pointer into the subobject’s function calling the timer. GetWorld() would be called from the passed pointer.