前提・実現したいこと
お世話になております.チュートリアルのブロック崩しを作り終えたので,新しいギミックを追加しようとしたところ,エラーが出ました.お助けくださいませ.
実現したいことは,ボールがバーに当たった時に,ボールを加速させるというものです.
該当のソースコード
c#
1// Bar.cs(バーにアタッチしているスクリプト) 2using System.Collections; 3using System.Collections.Generic; 4using UnityEngine; 5 6public class Bar:MonoBehaviour 7{ 8 public GameObject obj; 9 Ball ball; 10 // Use this for initialization 11 void Start() 12 { 13 ball = obj.GetComponent<Ball>(); 14 } 15 16 void OnCollisionEnter2D(Collision2D col) 17 { 18 ball.Accelerate(); // 1 19 } 20} 21
c#
1// Ball.cs(ボールにアタッチしているスクリプト) 2using System.Collections; 3using System.Collections.Generic; 4using UnityEngine; 5 6public class Ball : MonoBehaviour { 7 const int MIN_SPEED = 10; 8 const int MAX_SPEED = 150; 9 Rigidbody2D rb; 10 11 // Use this for initialization 12 void Start () { 13 rb = GetComponent<Rigidbody2D> (); 14 rb.AddForce(Vector2.down*MIN_SPEED-Vector2.right, ForceMode2D.Impulse); 15 Debug.Log(rb); 16 } 17 18 // Update is called once per frame 19 void Update () { 20 Accelerate(); // 2 21 } 22 23 public void Accelerate(){ 24 Debug.Log(rb); 25 rb.velocity *= 1; // 本当は下の文が正しいですが,諸事情により加速しないような記述をしています(同じエラーが出ることには変わりありません) 26 //rb.velocity = rb.velocity.normalized * MAX_SPEED; 27 } 28 29 public void Decelerate(){ 30 rb.velocity = rb.velocity.normalized * MIN_SPEED; 31 } 32}
エラーが出るのは,長たらしいコメントを書いた部分です.ここで,rb
がNULLになるときがあります.そのNULLになるときというのは,コメントで1と示してある部分からAccelerate()
を呼んだときです.2側から呼んだときは必ずNULLではありませんでした.ちなみに上記2つとは別のスクリプトからDecelerate()
を呼んでも同じ現象が起こりました.
発生している問題・エラーメッセージ
UnassignedReferenceException: The variable rb of Ball has not been assigned. You probably need to assign the rb variable of the Ball script in the inspector. UnityEngine.Rigidbody2D.get_velocity () Ball.Accelerate () (at Assets/Objects/Ball/Ball.cs:41) Bar.OnCollisionEnter2D (UnityEngine.Collision2D col) (at Assets/Objects/Bar/Bar.cs:23)
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/05/31 13:31 編集
2018/05/31 13:33
2018/05/31 13:35
2018/05/31 13:45
2018/05/31 13:46
2018/05/31 13:51
2018/05/31 13:55
2018/05/31 13:59
2018/05/31 14:01
2018/05/31 14:06
2018/05/31 14:06
2018/05/31 14:07
2018/06/02 01:58