我希望将我的健康状况显示为GUIText,并在玩家点击时减少。如何根据我的健康脚本编码?
这是我的健康状况
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;
}
更新:我不想显示敌人的健康,这段经文附着在每个敌人身上
答案 0 :(得分:2)
您可以通过以下操作轻松地使用C#在GUI上显示:
var myNiceVariable = "Showing the health values!";
var guiText = GameObject.Find("GUI Text").GetComponent(GUIText);
guiText.text = myNiceVariable;
或者您可以使用OnGui方法,您可以添加到您的脚本中:
void OnGui(){
GUI.Label(new Rect (5,5,10,100), "Health: " + hp);
}
答案 1 :(得分:2)
我建议你总是使用OnGui方法来显示游戏的界面
void OnGUI(){
GUI.color = Color.red;
GUI.Label(new Rect (20,20,200,20), "Health = " + hp);
}
您需要了解此代码所需的所有文档:
GUI.Label http://docs.unity3d.com/ScriptReference/GUI.Label.html OnGui方法:http://docs.unity3d.com/ScriptReference/MonoBehaviour.OnGUI.html
希望这对您有所帮助,请问您是否对此代码有任何疑问!