ตอนนี้ Unity 4.6 ก็ออกมาพร้อมกับ UI ใหม่ก็เลยอยากจะลองเอามาใช้ทำ Player Status
มาเริ่มกันเลยกันครับ
1. ให้ทำการสร้าง UI Panel โดยไปที่ GameObject -> UI - > Panel
2. จากนั้นให้ทำการเลือก Panel แล้วทำการปรับขนาด Panel (โดยการ กดปุ่ม t แล้วปรับขนาด)
3. แล้วทำการปรับ Anchors ดังภาพ
6. จากนั้นให้ Import รูปสำหรับทำ HP/MP Bar
7. จากนั้นนำ Image Bar ไปไว้ที่ Source Image ทำการปรับสีและ Image Type และ Properties อื่นๆ ดังรูป
9. จากนั้นให้ทำการสร้างตัวแปร int อีก 4 ตัวสำหรับ (playerHealth, maxPlayerHealth, playerMagic, maxPlayerMagic) และทำการ เลือกช่อง Inspector (เพื่อใช้สำหรับปรับค่าทดสอบ)
10. ในส่วนของ State 1 ให้ทำการเพิ่ม Call Method Action จำนวน 2 Action โดยมีการส่ง Parameters 3 ตัว(String, int, int) ดังภาพ
ทั้ง 2 Action ให้ทำการ Set
- Behavior : ให้ทำการลาก PlayerController จาก Player Object
- Method Name : SetStatusBar
- Parameter : 3
- ทำการเลือก Every Frame
Parameters ของ Action ที่ 1
- string : HP
- int : playerHealth
- int : maxPlayerHealth
Parameters ของ Action ที่ 2
- string : MP
- int : playerMagic
- int : maxPlayerMagic
// Variables
private Image healthBar;
private Image magicBar;
void Start()
{
animator = GetComponent<Animator>();
if(animator == null)
{
Debug.LogError("Need Animator Component!!!!");
}
// Get Component ของ healthBar / magicBar
healthBar = GameObject.Find("HPBar").GetComponent<Image>();
magicBar = GameObject.Find("MPBar").GetComponent<Image>();
}
// Function สำหรับคำนวณ Status Bar
public void SetStatusBar(string barType, int currentValue, int maxValue)
{
if(healthBar == null || magicBar == null)
return;
switch(barType)
{
case "HP" :
healthBar.fillAmount = (float)currentValue / (float)maxValue;
break;
case "MP" :
magicBar.fillAmount = (float)currentValue / (float)maxValue;
break;
}
}
เท่านี้ก็สามารถนำไปประยุกต์ใช้งานต่อได้ครับ
ปล. นี่เป็นเพียง 1 วิธีในการทำนะครับ มีอะไรแนะนำได้นะครับ