実現したいこと
Unityの教科書(猫本)のチャプター5でエラーが出たので解消したい
前提
Unityの教科書という書籍に従ってゲーム制作を進めていたところ、
スクリプトを書き換えたところで以下のエラーメッセージが発生しました。
発生している問題・エラーメッセージ
NullReferenceException: Object reference not set to an instance of an object GameDirector.DecreaseHp () (at Assets/GameDirector.cs:18) ArrowController.Update () (at Assets/ArrowController.cs:38)
該当のソースコード1
C#
1using System.Collections; 2using System.Collections.Generic; 3using UnityEngine; 4using UnityEngine.UI; 5 6public class GameDirector : MonoBehaviour 7{ 8 GameObject hpGauge; 9 // Start is called before the first frame update 10 void Start() 11 { 12 this.hpGauge = GameObject.Find("hpGauge"); 13 } 14 15 // Update is called once per frame 16 public void DecreaseHp() 17 { 18 this.hpGauge.GetComponent<Image>().fillAmount -= 0.1f; 19 } 20} 21
該当のソースコード2
C#
1using System.Collections; 2using System.Collections.Generic; 3using UnityEngine; 4 5public class ArrowController : MonoBehaviour 6{ 7 GameObject player; 8 // Start is called before the first frame update 9 void Start() 10 { 11 this.player = GameObject.Find("player"); 12 } 13 14 // Update is called once per frame 15 void Update() 16 { 17 //フレームごとに等速で落下させる 18 transform.Translate(0, -0.1f, 0); 19 20 //画面外に出たらオブジェクトを破棄する 21 if(transform.position.y < -5.0f) 22 { 23 Destroy(gameObject); 24 } 25 26 //当たり判定 27 Vector2 p1 = transform.position; 28 Vector2 p2 = this.player.transform.position; 29 Vector2 dir = p1 - p2; 30 float d = dir.magnitude; 31 float r1 = 0.5f; 32 float r2 = 1.0f; 33 34 if(d<r1+r2) 35 { 36 //監督スクリプトにプレイヤと衝突したことを伝える 37 GameObject director = GameObject.Find("GameDirector"); 38 director.GetComponent<GameDirector>().DecreaseHp(); 39 40 Destroy(gameObject); 41 } 42 } 43} 44

バッドをするには、ログインかつ
こちらの条件を満たす必要があります。