How to construct object from `TSubclassOf<UMyObject>`

Suppose I have some UObject subclass called UMyObject and I have a TSubclassOf<UMyObject> MyClass that is a blueprint class derived from UMyObject, how do I create a new instance of MyClass and get a UMyObject* pointer to it?

UCLASS()
class UMyObject : public UObject { /*...*/ }
UMyObject* MakeMyObjectFromBlueprint(TSubclassOf<UMyObject> MyClass) {
    return ???;
}

It’s just:

UMyObject* MyObject = NewObject<UMyObject>(GetTransientPackage(), MyClass);
1 Like

doesn’t work properly for me …
it has very weird behavior, like the object is only half valid … it looks fine until i use a function from it, and then it acts like a nullptr obj …
the object works fine when i build it with ConstructObjectFromClass with blueprint.

If you don’t keep a strong reference to the object, it will get garbage collected eventually

Having a pointer member variable marked with UPROPERTY() will keep the object alive for as long as that variable exists

It depends on your case, but if the object that spawns the new object has a

UPROPERTY(EditAnywhere)
TSubclassOf<UMyObject> MyClass;

UPROPERTY()
TObjectPtr<UMyObject> MySpawnedObject;

and then you set MySpawnedObject when spawning, it should stay alive

MySpawnedObject = NewObject<UMyObject>(this, MyClass);

A bit more advanced, but you can also use AddToRoot() if you don’t store it to a member, and that will make the object unaffected by garbage collection, but then you need to keep track of it, and remove it from root respectively when not needed anymore

1 Like

oh thanks, that’s why!
for now i’ll just use BP_ContructObjectFromClass … i don’t need to make objects in mass =).