hi.
I would like to ask a question.
i have a actor “ABaseSoldier”.it has a sub actor “APikemenSoldier”.
i want to cast “ABaseSoldier” actor to “APikemenSoldier” actor.
this is my code:
ABaseSoldier* BaseSoldier= GetWorld()->SpawnActor<ABaseSoldier>();
/*
* Dothing
*/
TSubClass<ABaseSoldier > SoldierClass = GetSoldierClass();
// How to cast BaseSoldier to APikemenSoldier actor?
BaseSolider = Cast<SoldierClass >();//Is error
// Is it theoretically possible to change the class of an actor that has already spawned?
It’s not possible to change the class of an already spawned actor.
You have to spawn the actor already as the type you want.
If you do that you can use it as its type or as one of its parent types.
TSubClass<ABaseSoldier > SoldierClass = GetSoldierClass();
// This will spawn whatever type SoldierClass is
ABaseSoldier* BaseSoldier = GetWorld()->SpawnActor<ABaseSoldier>(SoldierClass);
// This will give you BaseSoldier as APikemenSoldier or a nullptr if SoldierClass was not a APikemenSoldier
APikemenSoldier* PikemenSoldier = Cast<APikemenSoldier>(BaseSoldier);
you could also spawn a APikemenSoldier directly and use it as base soldier
thank you,Can I use TSubClass or UClass* for Cast()?
I need get different UClass* from "GetSoldierClass() " function.then Cast to this UClass*.
Here’s an example:
TSubClass<ABaseSoldier > SoldierClass = GetSoldierClass();
// The SoldierClass may be a APikemanSolider , or it may be a ASwordsmanSolider.
ABaseSoldier Solider = Cast<SoldierClass >(BaseSoldier);
Have GetSoldierClass() be a function inside of an interface (eg. ISoldier).
Have all soldiers implement the interface ISoldier.
Then you can have GetSoldierClass() return a specific class in each variant
Each solder type presents it own class through the same command
The interface is like a contract that guarantees that the classes have an implementation of it’s functions.
Then you can just call attack on the base soldier and the more specific version can do whatever they want.
If you want to cast you can do this
ABaseSoldier* SomeSoldierAsBaseSoldier;
if (APikemenSoldier* Pikemen = Cast<APikemenSoldier>(SomeSoldierAsBaseSoldier))
{
// do what you want with Pikemen
}
else if (ASwordSoldier* SwordSoldier= Cast<ASwordSoldier>(SomeSoldierAsBaseSoldier))
{
// do what you want with SwordSoldier
}
You can always try casting and if it is not of that class it will return nullptr