Unity3d c#"Object reference not set to an instance of an object"?

Unity3d c# "Object reference not set to an instance of an object"?

` public class Shoot : MonoBehaviour {

 public GameObject shell;
 public Transform barrelEnd;
 public float launchForce = 200;

 void Update () {

     if (Input.GetButtonDown("Fire1"))
     {
         Fire();
     }
 }
 void Fire()
 {
     Rigidbody projectile;
     projectile = Instantiate(shell, barrelEnd.position, barrelEnd.rotation) as Rigidbody;
     projectile.AddForce(0, 0, launchForce);

 }
}

在 Unity3d 中,我只想实例化一个 shell 并启动它。当我玩的时候,它会实例化 shell 但它不会启动它,它只是掉落。我不明白为什么我一直收到这个错误。显然我已经创建了一个对象的实例,对吗?非常感谢任何帮助!

您的问题是您没有实例化 Rigidbody,您正在实例化包含 Rigidbody 作为组件的 GameObject

当您使用 as 并尝试将其转换为对象不是的对象时,它会设置转换 null。将演员表更改为 GameObject,然后使用 GetComponent 获得 Rigidbody,它应该可以工作。

projectile = Instantiate(shell, barrelEnd.position, barrelEnd.rotation) as GameObject;
Rigidbody rb = projectile.GetComponent<Rigidbody>();
rb.AddForce(0, 0, launchForce);

出现此错误的原因有很多。

确保在编辑器中分配 shellbarrelEnd。如果这样做了,那么您需要从刚刚实例化的对象中获取组件。

除非你的相机总是朝向Z轴,否则这行代码就会有问题projectile.AddForce(0, 0, launchForce);

如果这是一个带有四处移动的相机的 FPS 游戏,请使用 cameraTransform.forward 让子弹始终从相机射出 forward/away。

public GameObject shell;
public Transform barrelEnd;
public float launchForce = 200;

Transform cameraTransform;

void Start()
{
    cameraTransform = Camera.main.transform;
}

void Update()
{

    if (Input.GetButtonDown("Fire1"))
    {
        Fire();
    }
}
void Fire()
{
    GameObject tempObj;
    tempObj = Instantiate(shell, barrelEnd.position, barrelEnd.rotation) as GameObject;
    Rigidbody projectile = tempObj.GetComponent<Rigidbody>();

    projectile.velocity = cameraTransform.forward * launchForce;
}
  1. 确保您有 shellbarrellEnd 的值。您可以从 unity 编辑器或在代码
  2. 的启动函数中执行此操作
  3. 在调用 rb.AddForce(0, 0, launchForce); 之前检查 rb 是否为 null。如果为 null,Scott 的方法将更有意义。