Access subclass through base
I'm trying to access a method within a gameobjects script without knowing the scripts name. What I do know is that the scripts base is an abstract class "entityScript" which it inherents a few things like health and damagedealt.
With the following code I am able to get the first Vector3 out of an array "MovePattern" that has been assigned by my "unknown" script
GameObject mover = movers [pos];
var scriptEnemy = mover.GetComponent<entityScript> ();
targetpositions [pos] = mover.transform.position + 32f * scriptEnemy.MovePattern[0];
The abstract base class
public abstract class entityScript : MonoBehaviour {
public int health;
public int damageDealt;
public Vector3[] Movepattern = new Vector3[5];
} }
And one example of the subclass that I want to find and use methods from without knowing the name.
public class simpleEnemy : entityScript {
// Use this for initialization
void Start () {
health = 10;
damageDealt = 1;
//Movepattern = new Vector3[]{Vector3.down, Vector3.down, Vector3.left, Vector3.right, Vector3.up};
}
public Vector3[] getMovePattern() {
Movepattern = new Vector3[]{Vector3.down, Vector3.down, Vector3.left, Vector3.right, Vector3.up};
return Movepattern;
}}
Note that in this scenario the method I want to access is "getMovePattern" which will be the same name in every other subclass, but with different contents. So to summarize in once question, how do I access the methods in subclasses through the base class?
Answer by Zodiarc · Nov 04, 2016 at 12:19 PM
What you are trying to do is impossible by design and is against oop-programming rules. If you need to access a method from a subclas in its superclass that means that your overall design is flawed. Try the composition over inheritance principle https://en.wikipedia.org/wiki/Composition_over_inheritance
Or in your special case you could use the Template Method Pattern.
Short example:
public abstract class Entity : MonoBehaviour {
public Vector3[] getMovePattern() {
return this.getSpecialMovePattern();
}
protected abstract Vector3[] getSpecialMovePattern();
}
public class Enemy : Entity {
protected override Vector3[] getSpecialMovePattern() {
return new Vector3[]{Vector3.up, Vector3.down};
}
}
Thank you, I used your second alternative and it works just as I wanted it to now.
It may be against OOP rules (that's subjective,) but it's common to check for a subclass: Enemy e1 = someEntity as Enemy; if(e1!=null)
.. .