2012-09-10 46 views
-1

MissingReferenceException:類型'GameObject'的對象已被破壞,但您仍然嘗試訪問它。您的腳本應該 或者檢查它是否爲空或者您不應該銷燬該對象。 UnityEngine.Object.Internal_InstantiateSingle(UnityEngine.Object 數據,POS的Vector3,四元數腐)(在 C:/BuildAgent/work/d9c061b1c154f5ae/Runtime/ExportGenerated/Editor/UnityEngineObject.cs:44) UnityEngine.Object.Instantiate( UnityEngine.Object original,Vector3 position,Quaternion rotation)(在 C:/BuildAgent/work/d9c061b1c154f5ae/Runtime/ExportGenerated/Editor/UnityEngineObject.cs:53) Gun.Update()(在J:/ WAR/Assets /Scripts/Gun.cs:16)我在拍攝時遇到錯誤

這就是錯誤我得到這裏我換槍類

代碼3210
using UnityEngine; 
using System.Collections; 

public class Gun : MonoBehaviour { 

    public GameObject bullet = null; 
    public float bulletSpeed = 500f; 

    void Update() { 
     if (Input.GetKeyDown (KeyCode.Mouse0)) { 

      /* 
      * Instantiate the bullet using the prefab and store it into the shot variable 
      */ 

      GameObject shot = GameObject.Instantiate(bullet, transform.position + (transform.forward * 2), transform.rotation) as GameObject; 

      /* 
      * Adding force 
      */ 
      shot.rigidbody.AddForce(transform.forward * bulletSpeed); 
     } 
    } 
} 
+0

它看起來像你試圖實例化一顆子彈,但是,你將子彈設置爲null,並在提供的代碼中沒有設置它爲別的東西。您不能使用空對象。 –

+0

GameObject看起來像一個Base類,所以你可能想要一個類型爲GameObject的類Bullet,因此設置bullet = new Bullet()。 –

+0

@ user1526784查看我的答案的例子。 –

回答

2

問題是,子彈GameObject爲null,並且因爲它尚未設置,所以當他試圖實例化一個空對象時,它會引發異常。

你可以做什麼取決於gameobject。您可以使用GameObject.Find獲取GameObject項目符號,然後將其分配給項目符號var。

public GameObject bullet = GameObject.Find("NameOfTheBulletGameobject"); 

另一種可以做到這一點的方法是將子彈gameobject拖放到檢查器中的變量上。

public GameObject bullet; 

然後,將實際的子彈對象拖到腳本中的子彈變量中,在檢查器中。

希望它有幫助!

+0

@ user1526784有幫助嗎? –