0
\$\begingroup\$

It was worked fine previously, but after some point, it's not working.

This is the code. It's not a pseudo code, actual code in game:

public Text healthText;

void Start() {
    healthText = GameObject.Find("UI/InGameUI/CharacterStatus/HealthText").GetComponent<Text>();
    }

void Update() {
    if(healthText) {
        print(health);
        // healthText.text = Time.deltaTime.ToString();
        healthText.text = "HP: " + health.ToString();
        // healthText.text = "HP: " + health;
    }
}

variable "health" is float value. I just want to print it to the screen, but it's always prints "Health: 100" even it changes.

So I printed the value to the console, but it prints well in the console and only text components was not printed properly.

So I printed Time.deltaTime instead of the health and it works!

Seriously, what the hell is happening? Is this a bug? If health variable wasn't changed, it should be also printed 100 in the console, but it's not!

Try this to another text component, still not working.

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

not sure what version of unity your using but I never use the full hierarchy path to my game objects, secondly since your declaring healthText as public, instead of the GameObject.Find() which by the way is an expensive as far as cpu hit call, you can just select the gameobject that script is attached to then in the inspector panel click the little lock in the top right corner so that the inspector doesn't change, select the text object in the hierarchy, drag and drop it to the healthText field of your script in the inspector and get rid of the GameObject.Find in your start method. doing it like this creates a "reference" as unity calls it to the exact specific gameobject that you drag and drop. Should solve your problem perfectly :)

also don't forget to click the lock again to unlock the inspector :)

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .