How to instantiate a UCLASS(Blueprintable) in C++?

Hey guys,

I want to use the UAutomationPerformanceHelper (it is a blueprintable class) in my c++ class, but I always get some error. Would you guys mind teaching me how to instantiate a blueprintable class in c++?

Thanks

Bests

YL

I had to do something similar working with the Wwise audio plugin, which implements an animation notify class via blueprint.

There are some helpers you can use in a class constructor to get a pointer to you blueprint’s UClass:

static ConstructorHelpers::FClassFinder<UAnimNotify> AkEventBPClassFinder(TEXT("/Wwise/AnimNotify_AkEvent"));
if (!AkEventBPClassFinder.Succeeded())
{
	AudioAnimNotifyClass = nullptr;
}
else
{
	AudioAnimNotifyClass = AkEventBPClassFinder.Class.Get();
}

You can instantiate an object of that type using the NewObject function. In the example below I am instantiating an object of type AnimNotify_AkEvent using the UClass object. Note however that I use the parent class, UAnimNotify, in the template arg to NewObject.

UAnimNotify* PointerToInstantiatedObject = NewObject<UAnimNotify>(AnimSequence, AudioAnimNotifyClass);

So this would return a pointer of type UAnimNotify*, but it is instantiated as a more specific type, namely the UClass type you supplied. . You can check that the object you instantiated’s class equals your blueprint’s UClass, and it should be the same.

If you want to manipulate UProperties or call UFunctions specific to your blueprint class within C++, that is more difficult, but possible; you have to use the reflection system. This can lead to messy code pretty fast-- I would highly suggest trying to incorporate as much core behavior as possible into the base C++ class, or create an additional C++ child class for the blueprint to inherit from so you can avoid having to do this, because now you’re writing C++ code that relies on special knowledge of the blueprint’s class structure, which is probably making your spidey-programmer sense tingle as one of those “you can do it, but should you?” moments…

for (TFieldIterator<UProperty> FieldIt(AudioAnimNotifyClass); FieldIt; ++FieldIt)
{
	UProperty* Prop = *FieldIt;
	const FString FieldName = FieldIt->GetName();
	if (FieldName == TEXT("Event"))
	{
                blah blah blah

When you use NewObject, there is an arg called Outer. Outer is essentially who has ownership over this new object, which creates a graph / hierarchy in your data that is important for stuff like garbage collecting and serialization.

eg If I was creating a new anim notify to place in an anim sequence, I would give the UAnimSequence object as the outer, etc. If it’s a throw away, temp object, there is a special TransientPackage you can use as the outer.

Hi guys, I used the NewObject to instantiate it. But I got a new error about ensureAsRuntimeWarning condition failed: OuterWorld != nullptr. Do you know about this?

Even if you get “some error” please paste it here

Thank you, very helpful!