1. 程式人生 > 其它 >Unity效果實現:扣血顯示

Unity效果實現:扣血顯示

在眾多遊戲中,敵人受到傷害後會彈出一個數值,顯示收到了多少傷害,我們用Unity3D來實現這一效果

實現思路:

在敵人收到攻擊後,生成一個文字控制元件,上面顯示敵人受到的傷害

程式碼1(掛在文字控制元件上):

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;

public class HpControl : MonoBehaviour
{
    private float timer = 0;
    public void SetText(string text)
    {
        GetComponent<TMP_Text>().text = text;
    }
    // Start is called before the first frame update
    

    // Update is called once per frame
    void Update()
    {
        timer += Time.deltaTime;
        if(timer>1)
        {
            Destroy(gameObject);
        }
        transform.Translate(Vector3.up * Time.deltaTime);
    }
}

程式碼2(掛在畫布上,控制文字控制元件的顯示與消失,和其中的內容):

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HpManager : MonoBehaviour
{
    //關聯HpText預製件
    public GameObject HpTextPre;
    // Start is called before the first frame update
    public void ShowText(string text)
    {
        GameObject go = Instantiate(HpTextPre, transform);
        go.GetComponent<HpControl>().SetText(text);
    }

    // Update is called once per frame
    void Update()
    {
        //面向攝像機
        transform.rotation = Quaternion.LookRotation(Camera.main.transform.forward);
    }
}