2016-12-14 117 views
-3

我想在Unity中製作遊戲,並且腳本在C#中。我有這個錯誤,當我做我的對象邁向NullReferenceException Unity

using UnityEngine; 
using System.Collections; 

public class Enemy : MonoBehaviour { 

    GameObject pathGO; 

    Transform targetPathNode; 
    int pathNodeIndex = 0; 

    float speed = 5f; 

    public int health = 1; 

    // Use this for initialization 
    void Start() { 
     pathGO = GameObject.Find ("Path"); 
    } 

    void GetNextPathNode(){ 
     targetPathNode = pathGO.transform.GetChild (pathNodeIndex); 
     pathNodeIndex++; 
    } 

    // Update is called once per frame 
    void Update() { 
     if (targetPathNode = null) { 
      GetNextPathNode(); 
      if (targetPathNode == null) { 
       // We've run out of path 
       ReachedGoal(); 
      } 
     } 

     Vector3 dir = targetPathNode.position - this.transform.localPosition; 

     float distThisFrame = speed * Time.deltaTime; 

     if (dir.magnitude <= distThisFrame) { 
      // We reached the node 
      targetPathNode = null; 
     } 
     else { 
      // Move towards the node 
      transform.Translate(dir.normalized * distThisFrame); 
      //Quaternion targetRotation = Quaternion.LookRotation (dir); 
      this.transform.rotation = Quaternion.LookRotation (dir); //Quaternion.Lerp (this.transform.rotation, targetRotation, Time.deltaTime); 
     } 
    } 

    void ReachedGoal(){ 
     Destroy (gameObject); 
    } 
} 

的NullReferenceException節點:對象引用未設置爲一個 對象Enemy.Update(實例)(在資產/ Enemy.cs:35 )這是錯誤。

+2

井'如果(targetPathNode = NULL)'應該是'如果(targetPathNode == NULL)' –

+1

@ŁukaszMotyczka燁。那就對了。這應該作爲錯字 – Programmer

+0

@ amand關閉,因爲沒有編號,請指出哪一行是第35行。這可能有助於未來。 –

回答

2

更改此:

if (targetPathNode = null) { 

這個

if (targetPathNode == null) { 

但統一超載==!=運營商將返回false,如果對象爲空。所以basicaly你的語句做的是:

if ((targetPathNode = null) != null) { 

,因爲你給它分配空值,這將是錯誤的。

但是!這仍然給你例外,因爲下一行是:

Vector3 dir = targetPathNode.position - this.transform.localPosition; 

又一次。你假設這個對象(你故意廢除)沒有被取消。在此行之前,您應該100%確定您的targetPathNode包含一些值(0x00除外,或者您可以將其稱爲null)。通過您的其他代碼簡單地判斷return關鍵字應該足夠了。例如:

if (!targetPathNode) return; 

Vector3 dir = targetPathNode.position - this.transform.localPosition;