(Unity)障害物に触れるとダメージを受ける(HPスライダーとHPテキストの実装)

(スクリプト)

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

public class MonsterHP : MonoBehaviour
{
    private int monsterMaxHP = 10;
    private int monsterHP;

    public GameObject effectPrefab;
    public AudioClip sound;

    public Slider HPSlider;
    public Text HPLabel;

    private void Start()
    {
        monsterHP = monsterMaxHP;

        HPSlider.maxValue = monsterMaxHP;
        HPSlider.value = monsterHP;
        HPLabel.text = "" + monsterHP;
    }

    private void OnTriggerEnter(Collider other)
    {
        if(other.CompareTag("Stick"))
        {
            monsterHP -= 1;

            HPSlider.value = monsterHP;
            HPLabel.text = "" + monsterHP;

            GameObject effect = Instantiate(effectPrefab, transform.position, Quaternion.identity);
            Destroy(effect, 0.5f);
            AudioSource.PlayClipAtPoint(sound, transform.position);
        }
    }
}

(設定)


(確認)

  • ダメージを受けるたびに、スライダーのバーが減少し、数字が小さくなれば成功です。