前提・実現したいこと
ttps://tech.pjin.jp/blog/2015/09/06/unity%e3%81%a72d%e3%82%a2%e3%82%af%e3%82%b7%e3%83%a7%e3%83%b3%e3%82%b2%e3%83%bc%e3%83%a0%e3%82%92%e4%bd%9c%e3%82%8d%e3%81%86%e2%91%a3-%ef%bd%9e/
を写しながら、Unityでゲームを作成しています。その際にエラーが発生しました。
発生している問題・エラーメッセージ
NullReferenceException: Object reference not set to an instance of an object Player.Update () (at Assets/Script/Player.cs:40)
該当のソースコード(C#)
Player
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Player : MonoBehaviour { public float flap = 600f; public float scroll = 10f; Rigidbody2D rigidbody2D; GameObject gameController; GameObject scoreGUI; void Awake() { rigidbody2D = GetComponent<Rigidbody2D>(); gameController = GameObject.Find("GameController"); scoreGUI = GameObject.Find("ScoreGUI"); } void Start() { rigidbody2D.isKinematic = true; } void FixedUpdate() { if (GameController.isPlaying == true) { rigidbody2D.velocity = new Vector2(scroll, rigidbody2D.velocity.y); } } void Update() { if (Input.GetKeyDown("space")) { if (GameController.isPlaying == false) { gameController.SendMessage("GameStart"); rigidbody2D.isKinematic = false; } rigidbody2D.velocity = Vector2.zero; rigidbody2D.AddForce(Vector2.up * flap, ForceMode2D.Impulse); } } void Move() { if (GameController.isPlaying == true) { rigidbody2D.velocity = new Vector2(scroll, rigidbody2D.velocity.y); } } void OnTriggerEnter2D(Collider2D col) { if (col.gameObject.tag == "CountZone") { scoreGUI.SendMessage("AddScore", 1); } } void OnCollisionEnter2D(Collision2D col) { if (col.gameObject.tag == "Death") { gameController.SendMessage("GameOver"); } } }
GameController
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class GameController : MonoBehaviour { private GameObject player; private GameObject start; private GameObject gameOver; public static bool isPlaying; void Awake() { player = GameObject.Find("Player"); start = GameObject.Find("Start"); gameOver = GameObject.Find("GameOver"); } void Start() { gameOver.SetActive(false); isPlaying = false; } void Update() { if (Input.GetKeyDown("a")) { SceneManager.LoadScene("bird"); } } public void GameStart() { start.SetActive(false); isPlaying = true; } public void GameOver() { if (isPlaying == true) { gameOver.SetActive(true); isPlaying = false; player.GetComponent<Player>().enabled = false; } } }
試したこと
エラーの日本語訳を調べる
入力するキーを変えてみる
補足情報
Playerで、エラーではないのですが
Rigidbody2D rigidbody2D;
の部分で
「'Player.rigidbody2D'は継承されたメンバー'Conponent.rigidbody2D'を非表示にします。
非表示にする場合はキーワードnewを使用してください。」
と出ています。
また、GameControllerは'Start'と表示するテキストに入れています。
現在実行すると初期位置から落ちず、動きません。エラーはspaceキーを押したときに表示されます。
デバッグを行ったところ、次のようになりました。
まだ回答がついていません
会員登録して回答してみよう