Static method does not have access to class variable

0

Hello, I have the following problem:    I have a static method that uses a variable of its class, but Unity gives me the following error:

  

\ Assets \ Scripts \ GameControl.cs (3.3):   Error CS0120: An Object Reference   is required for the field, method or   non-static property   'GameControl.healthText' (CS0120)   (Assembly-CSharp)

Here is the code for the "GameControl.cs" script (relevant code only):

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class GameControl : MonoBehaviour {

    public Text healthText;
    public static int healthBar = 100;

    public static void UpdateHealthBar(){
        healthText.text = "Health \n" + healthBar;
    }
}

Here is the code of the other file that is calling the method (only relevant):

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyScript : MonoBehaviour {
void Update(){
        gameObject.transform.Translate (dir.normalized * speed * Time.deltaTime,Space.World);

        if (Vector3.Distance (transform.position, target[wayPoint].position) <= 0.4f) {
            if (wayPoint < target.Length - 1) {
                wayPoint++;
                dir = target [wayPoint].position - gameObject.transform.position;
            } else {
                Destroy (this.gameObject);
                GameControl.healthBar--;
                GameControl.UpdateHealthBar();       //Aqui<<<
            }
        }
    }
}

Well, I realized that if I instantiate the class in the file to leave the class public only I do not get the error, however I want to avoid this solution. Why does this error occur, and how can I resolve it?

    
asked by anonymous 24.01.2017 / 02:24

1 answer

1

It occurs because static members are not part of the scope of the object, but of the class.

Assuming there is class Game with the following members

  • string Nome
  • string Produtor
  • static string Versao

Then, Versao will be accessible without instantiating the class

Game.Versao

The other two members will be accessible only in the class instance

Game game = new Game();
game.Nome;
game.Produtor;

One possible solution to your case is to make healthText also a static member. It looks like this you need, since all other members are also static.

    
24.01.2017 / 02:28