I’m currently trying to understand inheritance with regards to a base class that derives from MonoBehaviour.
This one’s kind of a two part-er. First, the Dictionary ‘actions’ that’s created in the base class only fires off the most recently added method despite the fact all options seem to be displaying just fine; it lists them all correctly in the game. I’m assuming that this is due to the way I’m setting up the inheritance with these objects.
So I’m starting to observe some undesired behavior from this design pattern and I suspect that this type of inheritance is just a bad solution to the whole system. Particularly:
- It’s rather verbose when it comes to descendant
Start()
methods - My
Dictionary<string, Action>
is acting very strange.
I’ve declared:
- GamePiece : MonoBehaviour
- Structure : GamePiece
- Generator : Structure
Currently I’m overriding GamePiece.Start()
and calling base.Start()
on every public override Start() for my each descendant.
So rather than directly ask a question about why the Dictionary isn’t working, I figured I’d start with the design itself. Is this just bad design and if so, is there a better way to approach inheriting from a MonoBehaviour?
GamePiece :
public class GamePiece : MonoBehaviour {
public Dictionary<string, Action> actions;
public virtual void Start () {
actions = new Dictionary<string, Action>();
actions.Add("Destroy", () => Destroy(this.gameObject));
}
}
Structure :
public class Structure : GamePiece {
public override void Start() {
base.Start();
}
}
Generator:
public class Generator: Structure {
Rigidbody2D rigid;
bool isGeneratingPower;
public override void Start () {
base.Start ();
actions.Add("Supply Power", () => SupplyPower());
rigid = gameObject.GetComponent<Rigidbody2D>();
rigid.angularVelocity = startSpeed;
}
}