Reputation: 36
I want to display my health as the GUIText and decreasing when the player hits. How to code based on my health script?
Here is my healthscript
using UnityEngine;
using System.Collections;
public class HealthScript : MonoBehaviour {
public static HealthScript instance;
public int hp = 1;
private GUIText scoreReference;
private GUIText highscoreReference;
private static int _highscore = -1;
public int highscore {
get { if (_highscore == -1)
_highscore = PlayerPrefs.GetInt("Highscore", 0);
return _highscore;
}
set {
if (value > _highscore) {
_highscore = value;
highscoreReference.text = _highscore.ToString();
PlayerPrefs.SetInt("Highscore", _highscore);
}
}
}
public bool isEnemy = true;
private static int points;
public void Damage(int damageCount) {
hp -= damageCount;
if (hp <= 0)
{
// Dead!
Destroy(gameObject);
points++;
scoreReference.text = points.ToString();
}
}
public void gameEnd() {
highscore = points;
points = 0;
}
void Start()
{
scoreReference = GameObject.Find("Score").guiText;
highscoreReference = GameObject.Find("HighScore").guiText;
scoreReference.text = points.ToString();
highscoreReference.text = highscore.ToString ();
instance = this;
}
UPDATE: I DON'T WANT TO DISPLAY ENEMY HEALTH, THIS SCRIPT WAS ATTACHED TO EVERY ENEMY
Upvotes: 0
Views: 2355
Reputation: 82
I recommend you to use OnGui method always to show the interface of the game
void OnGUI(){
GUI.color = Color.red;
GUI.Label(new Rect (20,20,200,20), "Health = " + hp);
}
All the documentation you need to understand this code is here:
GUI.Label http://docs.unity3d.com/ScriptReference/GUI.Label.html OnGui method: http://docs.unity3d.com/ScriptReference/MonoBehaviour.OnGUI.html
Hope this help you, ask if you have any troubles with this code!
Upvotes: 2
Reputation: 3185
You can use a variable to show on the GUI with C# easily by doing:
var myNiceVariable = "Showing the health values!";
var guiText = GameObject.Find("GUI Text").GetComponent(GUIText);
guiText.text = myNiceVariable;
Or you can use the OnGui method, you can add to your script:
void OnGui(){
GUI.Label(new Rect (5,5,10,100), "Health: " + hp);
}
Code taken from here and here.
Upvotes: 2