I have a state machine that controls my enemy AI. Each AI has a target which may be a Player, an obstacle, a shell, or even a Vector2 position.
I'm trying to abstract my "target" member, and my first thought was to use GameObject, then downcast to whichever type I need for different enemies. Examples below:
class StateController: MonoBehavior {
GameObject target;
FireAction action;
Update() {
action.Fire(this);
}
}
class FireAction: ScriptableObject {
public abstract void Fire(StateController c);
}
//Examples of different fire scripts:
class FireAtPlayer: FireAction {
public override void Fire(StateController c) {
Player p = c.target as Player;
//--use properties of Player object--
}
}
class FireAtPoint: FireAction {
public override void Fire(StateController c) {
GameObject t = c.target as Player;
//--use properties of GameObject object--
}
}
As you can see, my Fire methods would cast the target object at every call to Update. Will this negatively affect my game's performance? Note that I know for a fact what type of object the target is, so I'm not guessing when I'm casting. Thank you in advance of your help!
GameObject t = c.target as Player;
If I read your code correctly,c.target
already is aGameObject
. So you are downcasting it toPlayer
just to immediately upcast it toGameObject
again. That seems to be a bit pointless. The only reason I could see why one might do that is becauseas Player
will returnnull
when it's not a player, so you might be using it to detect if you are dealing with a player. But in that case you might rather want to useif (c.target is Player)
. \$\endgroup\$