2017-04-26 55 views
0

我是Unity的新手,我有一小部分代碼,實際上我是從Unity的教程中直接獲取的。本教程可以在這裏找到,在約12:46
https://www.youtube.com/watch?v=7C7WWxUxPZE如果有明確的參考,我爲什麼會得到一個空引用異常? (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); 
    } 
} 

我在兩個地方得到NRE:

rb.GetComponent <Rigidbody>(); 

rb.AddForce (movement); 
+0

只是一個僅供參考,如果你去觀看[上統一的網站教程系列(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。你應該在MonoBehaviour本身上致電GetComponent。那麼你需要採取調用的結果並指定爲rb

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

如果固定之後,你仍然得到NRE的rb.AddForce (movement);通話,這意味着遊戲對象的腳本連接到沒有Rigidbody附加到它,你將需要確保你也添加一個對象。

要超越什麼教程節目,你可能想要做的一件事就是把RequireComponent屬性您MonoBehavior類,以便腳本將會被自動添加Rigidbody遊戲對象,如果一個不存在。

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

現在,這是有道理的...感謝一堆! –

相關問題