在游戏中,游戏人物的血条可能会因为受伤或吃血瓶而长度变化,所以需要将血条的长度单独提出来作为一个变量,方便直接修改数值。
public float healthBarLength;
改变生命值函数如下:
void AddjustCurrentHealth(int adj){
curHealth += adj;
if (curHealth < ) {
curHealth = ;
} else if (curHealth > maxHealth) {
curHealth = maxHealth;
} if(maxHealth < ){
maxHealth = ;
}
healthBarLength = (Screen.width / * (curHealth / maxHealth));
}
在Update中调用
void Update () {
AddjustCurrentHealth ();
}
运行后查看效果,当修改CurHealth的值为-1的时候,它自动变为0。
但是当修改CurHealth为50的时候,发现血条长度始终为0,后来发现原来curHealth / maxHealth由于都是整数,所以结果是零,应该在maxHealth前面加float。
healthBarLength = (Screen.width / * (curHealth / (float)maxHealth));
这样运行再修改CurHealth值,对应的长度就正确了。
完整PlayerHealth.cs
public class PlayerHealth : MonoBehaviour {
public int maxHealth = ;
public int curHealth = ;
public float healthBarLength;
// Use this for initialization
void Start () { } // Update is called once per frame
void Update () {
AddjustCurrentHealth ();
} void OnGUI(){
GUI.Box (new Rect(,,healthBarLength,),curHealth + "/" + maxHealth);
} void AddjustCurrentHealth(int adj){
curHealth += adj;
if (curHealth < ) {
curHealth = ;
} else if (curHealth > maxHealth) {
curHealth = maxHealth;
} if(maxHealth < ){
maxHealth = ;
} healthBarLength = (Screen.width / * (curHealth / (float)maxHealth));
}
}
下面创建敌人的血条脚本:
在Unity编辑器的Assets/Scripts文件夹内,选中PlayerHealth,按键盘ctrl+d,复制一份,重命名为EnemyHealth。
双击打开Enemy,修改类名为EnemyHealth,然后将血条位置离top设为40,拖动它到Hierarchy里的cube上。
GUI.Box (new Rect(,,healthBarLength,),curHealth + "/" + maxHealth);
运行如图