C# 我有时在射击时会出错
MissingReferenceException:已删除类型为“GameObject”的对象 已销毁,但您仍在尝试访问它。你的剧本应该 检查它是否为null,或者不应销毁该对象。 UnityEngine.Object.Internal_实例化单(UnityEngine.Object 数据,矢量3位置,四元数旋转(at C:/BuildAgent/work/d9c061b1c154f5ae/Runtime/ExportGenerated/Editor/UnityEngineObject.cs:44) UnityEngine.Object.Instantiate(UnityEngine.Object原始,矢量3 位置,四元数旋转)(在 C:/BuildAgent/work/d9c061b1c154f5ae/Runtime/ExportGenerated/Editor/UnityEngineObject.cs:53) Gun.Update()(位于J:/W.A.R/Assets/Scripts/Gun.cs:16) 这是我得到的错误,这是我的枪类代码C# 我有时在射击时会出错,c#,unity3d,frame-rate,gameobject,C#,Unity3d,Frame Rate,Gameobject,MissingReferenceException:已删除类型为“GameObject”的对象 已销毁,但您仍在尝试访问它。你的剧本应该 检查它是否为null,或者不应销毁该对象。 UnityEngine.Object.Internal_实例化单(UnityEngine.Object 数据,矢量3位置,四元数旋转(at C:/BuildAgent/work/d9c061b1c154f5ae/Runtime/ExportGenerated/Editor/UnityEngineObject.cs:4
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);
}
}
}
问题是,bullet游戏对象是空的,因为它没有被设置,当他试图实例化一个空对象时,它会抛出一个异常 你能做什么取决于游戏对象。您可以使用
GameObject.Find
获取GameObject
项目符号,然后将其分配给项目符号变量
public GameObject bullet = GameObject.Find("NameOfTheBulletGameobject");
另一种方法是将bullet游戏对象拖动到inspector中的变量上
public GameObject bullet;
然后,只需获取实际的bullet对象并将其拖到脚本中的bullet变量上,即inspector中
public GameObject bullet;
希望有帮助 看起来您正试图实例化一个项目符号,但是,您将该项目符号设置为null,并且在提供的代码中没有将其设置为其他内容。您不能使用空对象。GameObject看起来像基类,因此可能需要GameObject类型的类项目符号,从而设置Bullet=new Bullet()。@user1526784请查看我的答案以获取示例。