Static function to spawn UObject which will be used in BP


I am struggling to make a static function to instantiate UObject in Blueprint (UE 4.8)



is depecrated in 4.8, I used


Here what i’ve tried


UFUNCTION(BlueprintCallable, Category="Objects")
  static UObject* SpawnObject(UClass* ObjClass);


UObject* ASomeClass::SpawnObject(UClass* ObjClass) 
         return NewObject<ObjClass>();

It gave me error

error C2974: ‘NewObject’ : invalid template argument for ‘T’, type

the T parameter is accepting class type, if I pass in class type it will work, but how am I supposed to spawn class of the parameter?

The template argument T in NewObject<T> is for when you know the type at compile-time. For a variable class like ObjClass, you can use this overload of NewObject (documentation):

UObject * MyObject = NewObject<UObject>(SomeOuter, ObjClass);

Where SomeOuter should be some other UObject (like an Actor) that is already registered to the world, or it can be NULL if you don’t want it to be part of the world. I think its garbage collection related. NewObject will return a UObject* but in your blueprint you can then proceed to cast it to whatever type you expect.

And now for something really cool

I bet you want the blueprint node’s return type to be the ObjClass you’re passing, like the SpawnActor and CreateWidget nodes. You can do this using a meta specifier in your UFUNCTION like this:

UFUNCTION(BlueprintCallable, Category="Objects", meta=(DeterminesOutputType="ObjClass"))
  static UObject* SpawnObject(UClass* ObjClass);

Wow, thanks for the reply

It works perfectly and also I don’t know that I need to put the meta to get the class I want

thanks a lot!