Static method has no access to class variable

Asked

Viewed 1,815 times

0

Hello, I have the following problem: I have a static method that uses a class variable, 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 from the "Gamecontrol.Cs" script (only relevant code):

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;
    }
}

Atribuição a vaiavél

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 instantiating the class in the file to leave the class only public does not get the error, but I want to avoid this solution. Why this error occurs, and how can I resolve?

1 answer

0


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

Assuming there is a class Game with the following members

  • string Nome
  • string Produtor
  • static string Versao

So, Versao will be accessible without instantiating the class

Game.Versao

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

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

A possible solution to your case is to make healthText be also a static member. It seems that this is what you need, since all other members are also static.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.