Health not working!

Hi, I’m fairly new to Unity and I’ve been having a problem with a first-person-shooter game I am making. In the game, you shoot at red balls to kill them and survive as long as possible. I have made a GUItext called “Health”, and have set the variable “health” to 100. I print out the health and it says 100. Good. The problem is that when you touch a red ball, it prints the health again. It’s supposed to go down from 100, but this time it says the same number health was when you last played the game and its negative! It never sets to 100 in the first place! The GUIText is also not working. I am using Unity 5.4.1. This is my code for the health:

private int Frame;
public GameObject Enemy;
private Vector3 spawnPosition;
private Quaternion spawnRotation;
public GUIText Health;
private int enemycount;
private int health;
void Start () {
    enemycount = 0;
    ResetHealth();
    Vector3 textPosition = new Vector3(0, 1, 0);
    Quaternion textRotation = new Quaternion(0, 0, 0, 0);
    Health = (GUIText)Instantiate(Health, textPosition, textRotation);
    Health.text = "Health: " + health;
    StartCoroutine(wait());
    Frame = 0;
    spawnPosition = new Vector3(Random.Range(165, -165),20,Random.Range(165, -165));
    spawnRotation = new Quaternion(0, -135, 0, 0);
    Instantiate(Enemy, spawnPosition, spawnRotation);
    enemycount++;
}
void ResetHealth()
{
    health = 100;
    Debug.Log(health);
}
IEnumerator wait()
{
    yield return new WaitForSeconds(1);

}
void FixedUpdate () {
    spawnPosition = new Vector3(Random.Range(165, -165), 20, Random.Range(165, -165));
    spawnRotation = new Quaternion(0, -135, 0, 0);
    Frame++;
    if (Frame % 100 == 0 && enemycount < 20)
    {
        Instantiate(Enemy, spawnPosition, spawnRotation );
        enemycount++;
    }
}
void UpdateScore()
{
    Health.text = "Health: " + health;
}
public void hurt()
{
    Debug.Log("Hurtbefore" + health);
    health--;
    Debug.Log("Hurt" + health);
    UpdateScore();
    wait();
}

Any help is greatly appreciated.

Hi

Before helping you on your way I’m going to assume you’re using GUIText because of legacy reasons. If not, I suggest you upgrade to 5.5 and use Text instead. Anyways, not important to your issue…

But first things first: something I notice in your Start() method :

Health = (GUIText)Instantiate(Health, textPosition, textRotation);

Is there a reason why you’d instantiate an object with a copy of itself? Is this even necessary? Normally your GUI Text object should be there by reference (I mean: you made it public for a reason, probably to assign it in the inspector of the script).

Look into that first. And could you also elaborate on when exactly the “hurt()” method is called? Is that on collision with the red ball? If so, could you post that script too?

Kind regards,

Koen Matthijs