NewObject And StaticClass() argument

Hi Everybody
I’m practicing with the C++ in the Unreal Engine: In my project I have one UObject A which has a pointer UObject B (e.g. UObjectB* objB), now during the initializzation of class A I also create class B as following

objB = NewObject();

Now if I try to get the world reference in a method of B I always got Nullptr, I found a way to overcome this issuse, which was to pass in the NewObject function the parameter “this” and “UObjectB::StaticClass()”.

objB = NewObject(this, UObjectB::StaticClass())

In this way my instance is able to get the wrold pointer…why is that? When should I use StaticClass() instenad of no arguments??

Thanks for the attentiton

Egon

Hello,

When creating New Objects you always have to provide inputs.
Usually the fist argument is the “Outer” class. Which is the class that created the object.

GetWorld() basically runs along the Outer classes untill it finds the world.
It’s defined as this in UObject:

// UObject::GetWorld() implementation
if (UObject* Outer = GetOuter())
{
    return Outer->GetWorld();
}

So you always need to pass in an object as the first parameter when calling NewObject();

Regarding the question to ::StaticClass(), that will be used when defining the type of object / class to create.
So leaving it empty will Create a normal UObject, but passing in UObjectB::StaticClass() will create a UObjectB object.

~ Dennis “MazyModz” Andersson