Uobject begin play() equivalent

The are right. UObject doesn’t know is World exist. When you create your UObject dynamically with NewObject function, you should pass an Outer(basically “Owner”) - some actor in the world.

To make it work out-of-box:

  1. Create your own BeginPlay() function

  2. Override PostInitProperties() function(called after the C++ constructor) and call your BeginPlay() in it. But you should be carefull, this function is called in editor too, so you should first check, if World exist.

    void UMyObject::PostInitProperties()
    {
    Super::PostInitProperties();

     //Called in game, when World exist . BeginPlay will not be called in editor
     if(GetWorld())
     {
        BeginPlay();
     }
    

    }

  3. Override GetWorld() function in your UObject

    UWorld* UMyObject::GetWorld() const
    {
    // Return pointer to World from object owner, if we don’t work in editor
    if (GIsEditor && !GIsPlayInEditorWorld)
    {
    return nullptr;
    }
    else if (GetOuter())
    {
    return GetOuter()->GetWorld();
    }
    return nullptr;
    }

Thats all, now you have BeginPlay() for your UObject.
Have a nice day)

4 Likes