Cast subclass

Hi guys

I’m trying to get an object from a TArray

UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Weapon)
TArray<TSubclassOf<class AWeapon> > Weapons;

Here’s what I’m doing

AWeapon* weapon = Cast<AWeapon>(Weapons[0]);
weapon->OnFire(GetControlRotation());

I’m putting an object who’s a subclass of AWeapon through the editor, but when I want to fire, it’s always NULL. Is because the affectation is in the editor or am I wrong somewhere else?

Thanks a lot!

It’s not NULL, it crashes because you casting object to unrelated class. TSubclassOf is kind of over-mainstreamed and people forget that this is really UClass* just with limiting options to specific subclass. UClass* is representative of class in reflection system and it’s used to point to specific class as C++ does not really let you to do it outside of templates. So they are not objects of a weapon class, it class it self and you need to spawn those weapons first from that class with:

()->SpawnActor<AWeapon>(Weapons[0]);

But considering you seem you want to create inventory, you need to spawn all weapons from that array to another array that will make inventory.

I’m not sure if it’s an inventory or not, but it doesn’t work. And it would make sens, because there’s nothing in Weapons[0] since my player starts with no weapons. (Mainly because I’m not able to add him one in the first place.)

Well definitly, you need to check if inventory is empty :stuck_out_tongue: but also you gonna have crashing caused by wrong casting with this code you made

Haha Ok, I’ll mark your response as the answer, but I’m clearly missing some pieces to this puzzle.

1- I want to add a weapon to my TArray Weapons, which is my character weapons, before the game launch. In the AFPSCharacter constructor if it’s possible.
Something like: Weapons[0] = new AAssaultRifle();
Which doesn’t work.

2- I want in the OnFire event of my character class, which is called when the player pull the trigger, to retrieve the content of the weapon at Weapons[0], which I can't be sure of the type, so I want to store it in a AWeapon variable since it'll be the parent class of all my weapons, and call their OnFire method.

I’ve added you my graph. I hope it’s more clear this way! I can send you my code too if you have the time, it would be awesome. Thanks!

You can’t do that in costructor, constructor is called when CBO is created before everything is initiated. You need to do that in BeginPlay and obviuesly using SpawnActor. Never use new on UObject class.

On point 2 i dont know what is wrong, i think you doing good here

Thanks, I think it’s working! Thanks for all the help!