Help with inherited variables of an abstract class

Hiya - so i think i’m at a bit of a misunderstanding here so if it isn’t too much trouble i need someone to explain to me where i’ve gone wrong here;

So i have an abstract class structured like this:


public abstract class Enemy : MonoBehaviour {
	// Physics
    protected Rigidbody2D rb;
    protected Collider2D col;

    protected virtual void Awake(){
		// Physics
            rb = this.GetComponent<Rigidbody2D>();
            col = this.GetComponent<Collider2D>();
            col.isTrigger = true;

Then a class inheriting it:

public class Whizzer : Enemy {
        protected override void Awake(){
              // Physics
              rb = GetComponent<Rigidbody2D>();
              rb.bodyType = RigidbodyType2D.Dynamic;
              rb.gravityScale = 0f;

              col = GetComponent<Collider2D>();
              col.isTrigger = true;

However the problem i’m having is that when i reference rb or col inside the Whizzer class it’s (i think) accessing the variables defined in the abstract Enemy class - this results in only one instance of a gameobject with this script working at a time since the last script to run assigns their rigidbody and collider as the variables in the abstract Enemy class

My question is how can i create seperate instances of the variables rb and col for every Whizzer class instance created whilst keeping the variables desired inside the abstract enemy class?

Alternative solutions accepted :wink:

Hi! This should work as is!

When you use an inherited variable, you’re not going to some sort of master Enemy script and asking it for its collider, rather you can imagine it like copying any variables and functions from the Enemy class and just pasting them into your Whizzer class.

You can treat your Whizzer class as if it just declares the collider and rigidbody just like in any other script (e.g. The rb = this.GetComponent<Rigidbody2D>();in your Enemy class does the exact same thing as the rb = GetComponent<Rigidbody2D>(); in your Whizzer class). This means that each Whizzer component will have its own collider. The same goes for any other classes who derive from Enemy.

The difference is that other scripts will realize these similarities between say your Goomba and HammerBro classes, and will be able to offer the same treatment to both of these, without having to make some list of compatible class types and cross checking the maybe-enemy against all of these. You don’t need to know every possible enemy, you just need to know that this is an enemy.

TL;DR The collider was inside Whizzer all along. Abstract classes don’t be like “Mom said it was my turn on the collider” (look at singletons if that’s what you want)

Hope this helps :smiley: