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:
-
Create your own BeginPlay() function
-
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(); }
}
-
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)