Array of subclass

Hello everyone.
I m currently making a ability system, where the abilities (that are just a derived class of UObject ) are stored in a TArray so i can change them later and use them ingame.


This is the declaration, since i’m going to use different types of abilities, and I want to create Blueprints for each of them, I use the “tsubclass”, so I can assign them from the inspector view.
The problem comes when I try to do anything with the abilities stored.
image
First of all, If I try to call a public method of the ability class called “castAbility”, I cant, because when I access the array position with the “[ ]” operator, it is treated as a UClass item. But if I try to do a Cast before calling the method, the cast allways fails.
image
I ’ m not sure why I’m getting this errors, anything helps.
Thanks

You are mixing up classes and object instances.
Can you show what “castAbility” method looks like ?

Yeah sure, but the CastAbility method does nothing at the moment, except showing some text on screen:
image
This is the .h file
image
And this the cpp one
As you can see, nothing special. However I cant call it from the character, with the array.
Can you help me with it?

Ok so you need to instantiate the abilities as objects.

Class/UClass/TSubclassOf types are just templates/descriptors of object types, but not actual objects.

In addition to your array of classes (which is basically the configuration), declare a second array for the instances :

UPROPERTY(EditAnywhere)
TArray<TSubclassOf<UAbility>> AbilitiesClasses;

UPROPERTY(Transient)
TArray<UAbility*> Abilities;

Then in something like PostInitializeComponents or BeginPlay (not in constructor!), instantiate the classes into objects :

voir APlayerEntity::BeginPlay()
{
    Super::BeginPlay();

    Abilities.Reserve(AbilitiesClasses.Num());
    for (const auto& Class : AbilitiesClasses)
    {
        UAbility* Ability = NewObject<UAbility>(this, Class);
        Abilities.Emplace(Ability);
    }
}

void APlayerEntity::CastAbility1()
{
    Abilities[0]->CastAbility();
}

Tanks mate, that’s it.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.