Changing UObject, Changing Settings

I have an ActorComponent called USquadComponent. This SquadComponent has 2 members that I currently care about:

UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Squad")
TSubclassOf<USquadFormation> FormationClass = nullptr;

UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Squad", meta = (ShowInnerProperties))
USquadFormation* SquadFormation = nullptr;

Now, when I’m in the editor and change my formation class I want the subobject SquadFormation to be changed to that new class and edit it’s values.
For example, I have a Circle Formation that has 2 additional members that are not in the parent class.

The problem is that just cannot find a way that either doesn’t crash the engine on startup or doesn’t let me save the Actor containing this component.
I looked a little bit through the source code and stumbled upon the UObject::Modify function and started to make use of it:

#if WITH_EDITOR
bool USquadComponent::Modify(bool bAlwaysMarkDirty)
{
    if(GEngine->IsEditor())
    {
	    GEngine->AddOnScreenDebugMessage(INDEX_NONE, 5, FColor::Red, 
		"SquadComponent Modify");

        if(FormationClass != nullptr)
        {
	        //this is crashing
	        if(!SquadFormation->IsA(FormationClass) && FormationClass->IsValidLowLevel())
	        {
	        }
        }
	return Super::Modify(bAlwaysMarkDirty);
}
#endif

Little side note, since I am using methods in the SquadFormation class I cannot use a struct because I want to make the SquadFormation to also be available to override in blueprints.

I think I am just missing some small things here since when I’m creating the SquadFormation in the constructor I am able to change the settings to my liking, I just don’t know how to make the class editable.

Could it be that you’re not checking if SquadFormation is null before executing the IsA function.

1 Like

my god… yea, it’s just me not realising a simple error xD

Also:

SquadFormation = Cast<USquadFormation>(CreateDefaultSubobject(
FormationClass->GetFName(), FormationClass, FormationClass, true, false));

crashes the editor so I have to use

SquadFormation = NewObject<USquadFormation>(this, FormationClass.Get(), FormationClass->GetFName());

Maybe someone can give some more context on why I have to use one rather than the other.
Anyway, at least I knew it was something small, thank you.

1 Like