こんにちは。
Unity初心者でちょっとプログラミングで詰まっていることもあり質問させていただきます。
前提・実現したいこと
Unityで自作ゲームを作っている者です。
一定方向に動く障害物を作ろうとしています。
ゲームオブジェクトに以下のコンポーネントを付けて、
・Sprite Renderer
・BoxCollider 2D
・Rigidbody 2D
・Obstacle (★後述)
・Block01 (★後述)
ゲームを開始しようとする「rb2Obstacle.MovePosition(direction * speed); 」(※)に対してNullReferenceExceptionが発生してしまいます。
※ 下記エラーの(at Assets/Scripts/Objects/Obstacle.cs:32)に該当
自力ではどこがNullになっているのか理解できなかったので、どなたかご教授下さい。
発生している問題・エラーメッセージ
NullReferenceException: Object reference not set to an instance of an object Obstacle.MoveObstacle (UnityEngine.Vector2 direction) (at Assets/Scripts/Objects/Obstacle.cs:32) Block01.FixedUpdate () (at Assets/Scripts/Objects/Block01.cs:25)
Obstacle
C#
1public class Obstacle : MonoBehaviour 2{ 3 public float speed; 4 5 private Rigidbody2D rb2Obstacle; 6 7 private void Start() 8 { 9 rb2Obstacle = this.GetComponent<Rigidbody2D>(); 10 } 11 12 public void MoveObstacle(Vector2 direction) 13 { 14 rb2Obstacle.MovePosition(direction * speed); 15 } 16}
Block01
C#
1public class Block01 : MonoBehaviour 2{ 3 private Obstacle Obstacle; 4 private Rigidbody2D rb2; 5 6 7 void Start() 8 { 9 Obstacle = GetComponent<Obstacle>(); 10 rb2 = GetComponent<Rigidbody2D>(); 11 } 12 13 private void FixedUpdate() 14 { 15 Obstacle.MoveObstacle(rb2.position * -1); 16 } 17 18}
補足情報
使用しているUnityは Version2019.4.0f1 Personal です。
回答2件
あなたの回答
tips
プレビュー