IMGUI实现
使用IMGUI中的HorizontalScrollbar控件来实现血条,改变其thumb的大小即可达到预期效果
- 右击Hierarchy界面,选择Create Empty,创建一个空的游戏对象,并将其改名为HP-IMGUI
- 在Asset中创建一个Scripts文件夹,在其中创建脚本,脚本代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HP_IMGUI : MonoBehaviour {
public float health; //血量,相当于HorizontalScrollbar的thumb大小
void Start()
{
health = 100.0f; //初始血量
}
void OnGUI()
{
if (GUI.Button(new Rect(Screen.width / 2 - 30, 70, 60, 40), "回血"))
{
health = health < 100.0f ? health + 1.0f : 100.0f;
}
if (GUI.Button(new Rect(Screen.width / 2 - 30, 120, 60, 40), "扣血"))
{
health = health > 0.0f ? health - 1.0f : 0.0f;
}
GUI.HorizontalScrollbar(new Rect(Screen.width / 2 - 100, 20, 200, 40), 0.0f, health, 0.0F, 100.0F);
}