前提・実現したいこと
unity2Dで横スクロールアクションのゲームを作っています。ミサイルの残弾数をアイテムを取得したら回復する、というものを作ろうと思い、サイトを参照しながら制作していたのですが、アイテムを取得しても回復せずに、困っています。回答よろしくお願いします。
参照サイト:https://mono-pro.net/archives/4919
発生している問題・エラーメッセージ
NullReferenceException: Object reference not set to an instance of an object ShellItem.OnCollisionEnter2D (UnityEngine.Collision2D col) (at Assets/scripts/ShellItem.cs:22)
該当のソースコード
unitychanが発射するミサイル弾のスクリプト using UnityEngine; using System.Collections; using UnityEngine.UI; public class PlayerMissile : MonoBehaviour { public LayerMask groundLayer; public GameObject Missile; public int shotCount; public Text shellLabel; private Rigidbody2D rigidbody2D; private Animator anim; private bool isGrounded; void Start() { anim = GetComponent<Animator>(); rigidbody2D = GetComponent<Rigidbody2D>(); shellLabel.text = "Missile:" + shotCount; } void Update() { if (Input.GetKeyDown("e")) { if (shotCount < 1) return; // ★追加 shotCountの数値を1ずつ減らす。 shotCount -= 1; // ★追加 shellLabel.text = "Missile:" + shotCount; anim.SetTrigger("Shot"); Instantiate(Missile, transform.position + new Vector3(0.4f, 1.2f, 0f), transform.rotation); // ショット音を鳴らす //GetComponent<AudioSource>().Play(); } } public void AddShell(int amount) { shotCount += amount; shellLabel.text = "Missile:" + shotCount; } }
`残弾数が回復するオブジェクトにアタッチしているスクリプト using System.Collections; using System.Collections.Generic; using UnityEngine; public class ShellItem : MonoBehaviour { private GameObject Missile; public int reward; // Use this for initialization void OnCollisionEnter2D(Collision2D col) { if (col.gameObject.tag == "UnityChan") { Destroy(gameObject); Missile = GameObject.Find("Missile"); PlayerMissile ss = Missile.GetComponent<PlayerMissile>(); ss.AddShell(reward); } } }
試したこと
サイトを参考してスクリプトを作成した。
補足情報(FW/ツールのバージョンなど)
unity
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。