[英]Unity3d c# “Object reference not set to an instance of an object”?
`公共课程拍摄: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并启动它。 当我玩游戏时,它将实例化外壳,但不会启动它,只会掉落。 我不明白为什么我总是收到这个错误。 显然我已经创建了一个正确的对象实例? 任何帮助深表感谢!
你的问题是你是不是实例化一个Rigidbody
,你实例化一个GameObject
含有Rigidbody
的分量。
当您使用as
并且尝试将其强制转换为不是该对象的对象时,它将强制转换设置为null
。 更改要转换成GameObject
,然后使用GetComponent
得到Rigidbody
,它应该工作。
projectile = Instantiate(shell, barrelEnd.position, barrelEnd.rotation) as GameObject;
Rigidbody rb = projectile.GetComponent<Rigidbody>();
rb.AddForce(0, 0, launchForce);
出现此错误的原因有很多。
确保在编辑器中分配了shell
和barrelEnd
。 如果完成了,那么您需要从刚刚实例化的对象中获取getComponent。
除非您的相机始终始终面向Z轴,否则这行代码projectile.AddForce(0, 0, launchForce);
将存在问题projectile.AddForce(0, 0, launchForce);
。
如果这是带有可移动相机的FPS游戏,请使用cameraTransform.forward
使其子弹始终从相机向前/向远方射击。
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;
}
shell
和barrellEnd
值。 您可以从unity编辑器中执行此操作,也可以在代码中的start函数中执行此操作 rb.AddForce(0, 0, launchForce);
检查rb
是否为null
。 如果为null,则Scott的方法更有意义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.