Unity实现敌人生命条

  在敌人物体身上添加 Slider,将Background设置为黑色,FIllarea设置为绿色,调整滑块大小。

  生命值减少代码设计如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class AnimalHunger : MonoBehaviour
{
    // Start is called before the first frame update
    public Slider hungerSlider;  //GUI中的滑块
    public int amountToBeFed;  //怪物的血量
    private int currentFedAmount = 0;  //当前损失血量
    private PlayerController playerController;  //计分和生命值的类
    void Start()
    {
        //初始化上述变量
        hungerSlider.maxValue = amountToBeFed;
        hungerSlider.value = 0;
        hungerSlider.fillRect.gameObject.SetActive(false);
        playerController=GameObject.Find("Player").GetComponent<PlayerController>();
    }

    // Update is called once per frame
    void Update()
    {

    }
    //当发生碰撞时,触发函数
    public void FedAnimal(int amount)
    {
        currentFedAmount += amount;
        hungerSlider.fillRect.gameObject.SetActive(true);
        hungerSlider.value = currentFedAmount;

        if(currentFedAmount>=amountToBeFed)
        {
            playerController.UpdateScores();
            Destroy(gameObject, 0.1f);
        }
    }
}

 

posted @ 2023-07-20 17:16  Kellen_Gram  阅读(82)  评论(0编辑  收藏  举报