SnowingGnat
SnowingGnat

Reputation: 11

How do I make a variable non-static without getting object reference error? (Beginner coder)

The update method in enemyHealth wants me to make targetHealth a static but if I do that then I won't be able to make unique enemies.

{
    public Text enemyHealth;

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        enemyHealth.text = EnemyVitals.targetHealth.ToString();
    }
}
{
    public double targetHealth = 100;

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        if (targetHealth <= 1)
        {
            Destroy(gameObject);
        }
    }
}

Upvotes: 1

Views: 39

Answers (1)

Luuke L
Luuke L

Reputation: 21

as far as I understand, this: enemyHealth.text = EnemyVitals.targetHealth.ToString(); tries to access targetHealth like you would access static classes for example Vector3.up. These static classes/methods allow you to use their methods without making an instance of that class. So in your case, you would need a reference to an EnemyVitals instance and call .targetHealth on that instance. You can for example instantiate one via EnemyVitals enemyVit = new EnemyVitals(); or declare a public field in your first class like so: public EnemyVitals enemyVit;, then in the editor drag and drop the EnemyVitals reference to that field. I think you might rather want to get the reference somehow otherwise in-game, for example with raycasting to possible enemy objects etc.. From what you posted it seems to me that the latter is more what you would want to go for.

Upvotes: 1

Related Questions