FPSで大事な要素といえば、アイテムドロップ。
敵を倒した時にアイテムが出るように実装をしてみた。
やることは結構簡単で、
- 倒された瞬間にアイテムを生成(Instansiate)
- プレイヤーがアイテムを取ったら自ら消える(Destroy)
の2つです。
まずアイテムを生成する方法から。
ここではアイテムを2つ用意して、どちらかを同じ確率でドロップするようにしてみました。
public Item item1; public Item item2; void itemDrop() { float rnd = Random.Range(0, 1f); if (rnd <= 0.5) { Instantiate(item1, this.transform.position, this.transform.rotation); } else { Instantiate(item2, this.transform.position, this.transform.rotation); } }
Instantiateを使うとアイテムをコピーします。
Itemにセットするのは、アイテムですが、忘れてはいけないのが、Prefab化したアイテム(プロジェクトウィンドウ内にある)をセットすること。

もし、ヒエラルキーウインドウにあるアイテムをセットしてしまいDestroyされた後に、Instantiateをしてしまうと以下のエラーが出ます。
“MissingReferenceException: The object of type ‘GameObject’ has been destroyed but you are still trying to access it.”
Instantiateを使ってアイテムを生成(コピー)する場合には、Prefab化されたオブジェクトを使うようにしましょう。

あとは、アイテムと衝突する必要はないので、Colliderの「Is Trigger」はチェックしておきましょう。
Itemクラスは以下の通り。
public class Item : MonoBehaviour { public enum ItemType{ HPRecover, Bullet } public ItemType type; private void OnTriggerEnter(Collider other) { Destroy(gameObject); } }
OnTriggerEnterは、プレイヤーがアイテムを触った時に呼ばれ、Destroyを呼ぶことでアイテムを消去しています。
プレイヤーの処理は以下の通り。
public class PlayerStatus:MobStatus { [SerializeField] GunController gun; public ParticleSystem recoveryEffect; public ParticleSystem bulletChargeEffect; public void getItem(Collider collider) { var item = collider.GetComponent<Item>(); if (item == null) { return; } else { if(item.type == Item.ItemType.HPRecover) { Life += 1; recoveryEffect.Play(); }else if(item.type == Item.ItemType.Bullet) { gun.Ammo += 20; bulletChargeEffect.Play(); } } } private void OnTriggerEnter(Collider other) { getItem(other); } }
取得したアイテムによって、HPを回復させたり、弾を増やしています。
プレイヤーが接触するコライダはアイテムだけではないので、最初の方で例外処理を記載することで、Null Pointerを回避するようにしています。
おわり。