- Home /
How to display health on screen as text?
Here is my script:
var health:float = 100;
function Damage(dmg:float){ health -= dmg; }
function Update (){
if(health <=0){
Destroy(gameObject);
}
}
I want to display the variable of health I have on screen. Thanks for any help
Answer by TheSOULDev · Jul 29, 2017 at 10:44 PM
The way you do this is the following - first you need to use the UI portion of Unity Engine. Do this by adding
using UnityEngine.UI;
Then, you need to create a variable of type Text - this will be the reference to your GameObject's Text component. Lastly, you will need to edit this Text component's text variable.
All in all, you would use something like this (in C#, sorry idk Java, but probably very similar):
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
public class YourScriptName : MonoBehaviour
{
public Text textbox;
void Start()
{
textbox = GetComponent<Text>();
}
void Update()
{
textbox.text = "" + health;
if(health <= 0)
Destroy(gameObject);
}
}
This is, of course, assuming that your text box is a child of the object this script is attached to. If it isn't you can either remove the Start function and add it in the editor by hand, or you can use FindObjectOfType, which I wouldn't recommend for Text.
Your answer
Follow this Question
Related Questions
General question/advice for displaying multiple variables on a gameobject 0 Answers
Display a Text/GUI on screen when triggerd with Fadein/Fadeout 1 Answer
Where can I find the scripts used in the Player State Machine & HUD/GUI Tutorials? 1 Answer
How do you get a GUI text to display a var like health? 4 Answers
Odd question... can a GUIText object be displayed upside-down? 2 Answers