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