(Unity)HPの減少に応じて表示テキストの色を変化させる方法

(スクリプト)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
 
public class TankHP_2 : MonoBehaviour
{
    public GameObject effectPrefab;
    public AudioClip sound;
 
    private int HP = 50;
    public Text HPLabel;
 
    private void Start()
    {
        HPLabel.text = "HP:" + HP;
        HPLabel.color = Color.green;
    }
 
    private void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.CompareTag("EnemyShell"))
        {
            HP -= 1;
 
            if(HP > 40)
            {
                HPLabel.color = Color.green;
            }
            else if(HP > 30)
            {
                HPLabel.color = Color.yellow;
            }
            else if(HP > 10)
            {
                HPLabel.color = Color.blue;
            }
            else
            {
                HPLabel.color = Color.red;
            }
 
            HPLabel.text = "HP:" + HP;
 
            Destroy(collision.gameObject);
            GameObject effect = Instantiate(effectPrefab, collision.transform.position, Quaternion.identity);
            Destroy(effect, 0.5f);
            AudioSource.PlayClipAtPoint(sound, transform.position);
        }
    }
}

(結果)

  • HPの数に応じて、HPテキストの色が変化すれば成功