Is there a way to create a new object where the template/typename can be determined dynamically?
Suppose I have a parent class (ParentClass) with two child classes (ChildA and ChildB). I want to be able to create a new object, but won’t know until runtime whether it’s going to be a ChildA or ChildB. What I want is to do something like this:
But this doesn’t work. The <> are not expecting a UClass* to be put between them. But I cannot figure out how to vary what goes between them. Is there a way?
if (!ClassToCreate->IsValidLowLevelFast()) {return;}
auto FreshObject = NewObject<UClassToCreate>(this,ClassToCreate->GetFName(),RF_NoFlags,ClassToCreate.GetDefaultObject());
Actually it is derived from UObject. The code I’ve posted is just an abstracted form of what I’m using to make things simpler. My classes are not actually called ParentClass, ChildA and ChildB! Granted, I probably should have written UParentClass, but I was just trying to convey the concept of parent/child classes. Sorry for the confusion.
Then the issue may be many different causes; how ChildB was built, where you assign to ClassToCreate, where you’re calling NewObject (or DefaultSubobject) from, etc.
If “this” static pointer isn’t a world member UObject, then you most likely get a crash/exception, as it’s meant to be “outer” of the new object you’ve just created.