NewObject()

Trying to get a function working which will allow me to instantiate a class chosen by the designer in blueprint.

The code currently is:

UEffectBase* UCodeFunctionLibrary::CreateEffect(TSubclassOf<UEffectBase> EffectClass, float magnitude, FVector direction)
{	
UEffectBase* CreatedEffect = NewObject<UEffectBase>(EffectClass);
CreatedEffect->initializeEffect(magnitude, direction);
return CreatedEffect;
}

The problem is that it always creates a UEffectBase - never what EffectClass actually is handed in as (ie. damage, knockback etc.). I’m assuming this is because I’m explicitly stating the type as UEffectBase in the NewObject call - but any attempt to put a variable or TSubClassOf in, ie. NewObject - just causes compile errors.

I’m sure this is possible, what is the syntax to get NewObject to instantiate a type of TSubObject?

Same problem here. Guys from here https://answers.unrealengine.com/questions/76747/properly-using-newobject.html posting about ConstructObject workaround, but it’s deprecated.

The first parameter to NewObject is the outer object. The class is the second parameter.

NewObject< UEffectBase >(Outer, EffectClass);

Most often you’ll pass this as the outer, though in a function library as above, that wouldn’t be a good idea. Most likely you’d want another parameter on the function so the caller could pass in the object to be used as the outer.

The answer linked above by @zulman has since been updated.

Is it necessary to do RegisterComponent also after this? and then UnregisterComponent?