2017-04-26 5 views
0

私はUnityを初めて使っています。実際にUnityのチュートリアルから直接取り出したコードが少しあります。チュートリアルでは、ここで見つけることができ、およそ12:46
https://www.youtube.com/watch?v=7C7WWxUxPZE明確な参照があるときに、Null参照例外が発生するのはなぜですか? (Unity)

でスクリプトが正常にゲームオブジェクトに添付されており、ゲームオブジェクトは、剛体コンポーネントを持っています。

チュートリアルは数年前ですが、私はAPIで物事を見て、この特定のビットについてはすべてが同じであるように見えます。ここで

はスクリプトです:

using System.Collections; 
using System.Collections.Generic; 
using UnityEngine; 

public class PlayerController : MonoBehaviour { 
private Rigidbody rb; 

void Start() 
    { 
    rb.GetComponent <Rigidbody>(); 

    } 


void FixedUpdate() 
    { 

    float moveHorizontal = Input.GetAxis ("Horizontal"); 
    float moveVertical = Input.GetAxis ("Vertical"); 

    Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);  

    rb.AddForce (movement); 
    } 
} 

私は2つの場所でNREを得る:

rb.GetComponent <Rigidbody>(); 

rb.AddForce (movement); 
+0

FYI、あなたが行くと、[ユニティのウェブサイト上のチュートリアルシリーズ](https://unity3d.com/learn/tutorials/projects/roll-ball-tutorial/moving-player?playlist=を見れば17141)の代わりにYouTubeの各ページにはビデオの下に書かれたコードがあり、あなたの作品を確認することができます。 –

+0

'rb'は明らかにインスタンス化されていないプライベートフィールドです。なぜ呼び出されたときに 'NullReferenceException'をスローしないと思いますか? –

+0

[NullReferenceExceptionとは何か、それを修正する方法は?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) ) – EJoshuaS

答えて

2

あなたはrbオブジェクトにGetComponentを呼び出すべきではありません。クラスMonoBehaviourGetComponentを呼び出す必要があります。その後、Rigidbodyを持っていない、これを固定した後、あなたはまだゲームを意味rb.AddForce (movement);コールのNREは、スクリプトが添付されているオブジェクトを取得した場合、その呼び出しの結果を取得し、rb

void Start() 
{ 
    rb = GetComponent <Rigidbody>(); 
} 

に割り当てる必要がありますそれに添付されているオブジェクトにオブジェクトを追加する必要があります。どのようなチュートリアルのショーを越えて行くために

が存在しない場合、スクリプトが自動にゲームオブジェクトにRigidbodyが追加されますので、あなたがやりたいことが一つのことは、あなたのMonoBehaviorクラスにRequireComponent属性を入れています。ただ、

using System.Collections; 
using System.Collections.Generic; 
using UnityEngine; 

[RequireComponent(typeof(Rigidbody))] 
public class PlayerController : MonoBehaviour { 
private Rigidbody rb; 

    void Start() 
    { 
     rb = GetComponent<Rigidbody>(); 

    } 


    void FixedUpdate() 
    { 

     float moveHorizontal = Input.GetAxis ("Horizontal"); 
     float moveVertical = Input.GetAxis ("Vertical"); 

     Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);  

     rb.AddForce (movement); 
    } 
} 
+0

これは意味があります...ありがとう! –

関連する問題