-1

MissingReferenceException:“GameObject”类型的对象已被销毁,但您仍在尝试访问它。您的脚本应该检查它是否为空,或者您不应该销毁该对象。UnityEngine.Object.Internal_InstantiateSingle (UnityEngine.Object data, Vector3 pos, Quaternion rot) (at C:/BuildAgent/work/d9c061b1c154f5ae/Runtime/ExportGenerated/Editor/UnityEngineObject.cs:44) UnityEngine.Object.Instantiate (UnityEngine.Object original , Vector3 位置, 四元数旋转) (在 C:/BuildAgent/work/d9c061b1c154f5ae/Runtime/ExportGenerated/Editor/UnityEngineObject.cs:53) Gun.Update () (在 J:/WAR/Assets/Scripts/Gun.cs: 16)

这就是我得到的错误,这里是我的枪类代码

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);
        }
    }
}
4

1 回答 1

2

问题是,子弹 GameObject 是空的,因为它没有被设置,当他试图实例化一个空对象时,它会抛出一个异常。

你能做什么取决于游戏对象。您可以使用GameObject.Find来获取GameObject项目符号,然后将其分配给项目符号变量。

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

您可以这样做的另一种方法是将子弹游戏对象拖到检查器中的变量上。

public GameObject bullet;

然后,只需将实际的项目符号对象拖到脚本中的项目符号变量上,在检查器中。

希望能帮助到你!

于 2012-09-10T12:53:55.100 回答