方法一、使用NGUI
Step0:導入NGUI包.建立一個UIRoot(2D)和一個Cube;
Step1:

Step2:設定參數
Step3:将下面代碼挂到Cube上:
using UnityEngine;
using System.Collections;
public class Enemy : MonoBehaviour {
public GameObject mSlider;//将前面建立的Slider拖到此處;
private GameObject uiRoot;
void Start () {
uiRoot = GameObject.FindGameObjectWithTag ("UIRoot");
}
void Update () {
Vector3 pos0 = transform.position;
Vector3 pos1 = Camera.main.WorldToScreenPoint (pos0);
//将螢幕坐标轉換為NGUI相機的世界坐标。
mSlider.transform.position = UICamera.currentCamera.ScreenToWorldPoint (pos1) + new Vector3 (-0.4f, 0.3f, 0);
//改變血量
if (Input.GetKeyDown(KeyCode.A)) {
mSlider.GetComponent<UISlider>().value += 0.1f;
}
if (Input.GetKeyDown(KeyCode.D)) {
mSlider.GetComponent<UISlider>().value -= 0.1f;
}
}
}
Step4:點選鍵盤A和D檢視運作結果如圖:
方法二、使用GUITexture
GUITexture是二維GUI中的紋理圖檔,在Scene視圖中不能顯示Texture的樣子,它的樣子隻能在錄影機中看到。
你需要将下面代碼挂到Cube上,再拖上對應的PNG圖檔。
using UnityEngine;
using System.Collections;
public class Enemy : MonoBehaviour {
public GUITexture HPTexture;//下圖紅色部分
public GUITexture backgroundOfHPTexture;//下圖白色部分
public GUITexture charactorTexture;//下圖太空人
public float percentOfHP = 0.3f;//血量百分比
// Update is called once per frame
void Update ()
{
Vector3 pos = Camera.main.WorldToViewportPoint(transform.position);
//GUITexture的位置是相對于錄影機螢幕的位置,左下角是(0,0,0)右上角(1,1,0)忽略Z坐标。
backgroundOfHPTexture.transform.position = new Vector3 (pos.x-0.15f, pos.y+0.15f, 0);
//設定相對于自身的坐标和大小。
backgroundOfHPTexture.pixelInset = new Rect(0,0,200f,10f);
HPTexture.transform.position = new Vector3 (pos.x-0.15f, pos.y+0.15f, 1);
HPTexture.pixelInset = new Rect(0,0,200f * percentOfHP,10f);
charactorTexture.transform.position = new Vector3 (pos.x-0.15f, pos.y-0.1f, 1);
charactorTexture.pixelInset = new Rect (0, 0, 128, 58);
transform.Translate (new Vector3 (1f * Time.deltaTime,0,0 * Time.deltaTime ));
}
}
最終效果圖: