TankHPを回復させるアイテム





HP回復アイテム
using UnityEngine;
using TMPro;
public class TankHP : MonoBehaviour
{
public int HP;
public TextMeshProUGUI HPLabel;
// ★追加
private int maxHP = 8; // 最大HP
public AudioClip itemSound;
public GameObject effectPrefab;
private void Start()
{
HPLabel.text = "" + HP;
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("EnemyShell"))
{
HP -= 1;
HPLabel.text = "" + HP;
if (HP < 1)
{
this.gameObject.SetActive(false);
}
}
}
// ★追加
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("HPItem"))
{
// HPアイテムを消す
Destroy(other.gameObject);
// 効果音を出す
AudioSource.PlayClipAtPoint(itemSound, transform.position);
// エフェクトを出す
GameObject effect = Instantiate(effectPrefab, other.transform.position, Quaternion.identity);
// エフェクトを消す
Destroy(effect, 1.0f);
// HPを「2」回復させる
HP += 2;
HPLabel.text = "" + HP;
// HPが最大値を超えないように制限する
if (HP > maxHP)
{
HP = maxHP;
HPLabel.text = "" + HP;
}
}
}
}


【Unity6版】BattleTank(全31回)
他のコースを見る




HP回復アイテム
using UnityEngine;
using TMPro;
public class TankHP : MonoBehaviour
{
public int HP;
public TextMeshProUGUI HPLabel;
// ★追加
private int maxHP = 8; // 最大HP
public AudioClip itemSound;
public GameObject effectPrefab;
private void Start()
{
HPLabel.text = "" + HP;
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("EnemyShell"))
{
HP -= 1;
HPLabel.text = "" + HP;
if (HP < 1)
{
this.gameObject.SetActive(false);
}
}
}
// ★追加
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("HPItem"))
{
// HPアイテムを消す
Destroy(other.gameObject);
// 効果音を出す
AudioSource.PlayClipAtPoint(itemSound, transform.position);
// エフェクトを出す
GameObject effect = Instantiate(effectPrefab, other.transform.position, Quaternion.identity);
// エフェクトを消す
Destroy(effect, 1.0f);
// HPを「2」回復させる
HP += 2;
HPLabel.text = "" + HP;
// HPが最大値を超えないように制限する
if (HP > maxHP)
{
HP = maxHP;
HPLabel.text = "" + HP;
}
}
}
}


TankHPを回復させるアイテム