Home > OS >  Instance of class not able to access variables
Instance of class not able to access variables

Time:10-23

I am new to Unity and have been doing C# for a while now. I currently have a problem where I am not able to access variables for New Instance of a class I created and I'm not sure what is happening let me explain.

[System.Serializable]
public class Boss : MonoBehaviour
{
    protected int maxhealth;
    protected int health { get; set; }
    protected int damage;

    public void TakeDamage(int hploss)
    {
        health -= hploss;
    }
}

And this is the beginning for what I am doing to create a new version of it

public class RollerBoss : Boss
{

    void Start()
    {

        Boss.maxhealth = 50;
        Boss.health = 50;
    }
}

I keep getting this error from Unity, and I am not sure why

Error CS0120: An object reference is required for the non-static field, method, or property 'Boss.health'

CodePudding user response:

Roller is a Boss. There is no need to explicitly point out that you want to access protected members inherited from Boss. In fact the C# compiler doesn't even understand that you are trying to do that. Rather, when you access Boss.member the compiler thinks that Boss is some variable that you have not defined.

Instead you can do this:

void Start()
{

    this.maxhealth = 50;
    this.health = 50;
}

And in C# this is already implied, so you can simply write:

void Start()
{

    maxhealth = 50;
    health = 50;
}

As an aside, if Roller does not define additional functionality it should not be its own class. Alternative solutions are to use a Builder or a Unity ScriptableObject

  • Related