Hello! I’m currently trying to get a generic method to instantiate a class working using NewObject. I made a blueprint function library and put a method in to instantiate any object (extending from UObject). However, when I call this method using PIE (haven’t tested anywhere else) it just freezes the editor with no data in the log. Here’s my method code:
UObject * UBlueprintUtils::InstantiateObject(TSubclassOf<UObject> type)
My current use for it is instantiating a blueprint class that I have: nothing special about it, just a class extending from UObject with a single variable (for now). I’ve gotten this to work in previous editor versions using ConstructObject, but that’s now deprecated. Any ideas on this?
Turns out that the code WILL eventually be executed (and it gets faster every time - it’s probably my computer specs holding it back), but this reveals another problem. When this code is run, it’s not returning an object of the type that I’m trying to instantiate, but returning a UObject. Casting to my desired class fails. Looking in the log, it’s giving me this error: Error Log - Pastebin.com
Still no luck on this, and my game can’t really progress until I have this working. Thanks!
Error suggest you trying to instantiate abstract class which are not intended to be spawned. So what exactly do you spawning?
Also if you use TSubclassOf, TSubclassOf becomes pointless here as there no point of selection limitation which TSubclassOf was made for, so use UClass*. You also should implement block on actors classes.
Alright, I will keep the class pointer in mind, thanks. I’m trying to create a blueprint extending from object. I’m not “spawning” so to speak, just trying to make a blueprint equivalent of a constructor basically.
Actually, that other answer DID work. It turns out that I need to set an outer class for this to work, which I haven’t been.
The problem has been solved! Turns out that I need to set the outer object for NewObject to work (which I wasn’t). Thanks to @isgoed for the answer in another one of my older questions about the same topic (Instantiating Instance of Blueprint Class - Blueprint - Epic Developer Community Forums). This is the code that I used:
UFUNCTION(BlueprintCallable, Category = Game)
static void InstantiateObject(UClass * ObjectClass, UObject * &CreatedObject);
void UBlueprintUtils::InstantiateObject(UClass * ObjectClass, UObject * &CreatedObject)
CreatedObject = NewObject<UObject>((UObject*) GetTransientPackage(), ObjectClass);