(サンプルコード)
using UnityEngine;
using UnityEngine.UI;
public class DestroyObjest1 : MonoBehaviour
{
public GameObject effectPrefab;
public GameObject effectPrefab2;
public AudioClip sound;
private int maxHP = 10;
private int currentHP;
private int lives = 5;
// ★5色スライダー
public Slider hpSlider;
public Image fillImage;
public Image backImage;
// ★5色スライダー
private Color[] lifeColors =
{
Color.red,
Color.yellow,
Color.gray,
Color.blue,
Color.green
};
// ★5色スライダー(上と色を1つずつ「すらす」のがポイント)
private Color[] backColors =
{
Color.white,
Color.red,
Color.yellow,
Color.gray,
Color.blue
};
private void Start()
{
currentHP = maxHP;
// ★5色スライダー
hpSlider.maxValue = maxHP;
UpdateSlider();
}
// ★5色スライダー
void UpdateSlider()
{
hpSlider.value = currentHP;
fillImage.color = lifeColors[Mathf.Clamp(lives - 1, 0, lifeColors.Length - 1)];
backImage.color = backColors[Mathf.Clamp(lives - 1, 0, lifeColors.Length - 1)];
}
void LoseLife()
{
if (lives > 1)
{
lives -= 1;
currentHP = maxHP;
}
else
{
currentHP = 0;
Destroy(gameObject);
GameObject effect2 = Instantiate(effectPrefab2, transform.position, Quaternion.identity);
Destroy(effect2, 1.0f);
AudioSource.PlayClipAtPoint(sound, transform.position);
}
}
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Beam"))
{
GameObject effect = Instantiate(effectPrefab, other.transform.position, Quaternion.identity);
Destroy(effect, 0.5f);
currentHP -= 1;
if (currentHP <= 0)
{
LoseLife();
}
// ★5色スライダー
UpdateSlider();
}
}
}
(実行結果)
・HPが0になるごとにスライダーの色が変化すれば成功