无法将类型"UnityEngine.GameObject"转换为"UnityEngine.Rigidbody"



我有一些错误!

UNITY 3D

    Rigidbody bullet = (Rigidbody)Instantiate(projectile, transform.position + transform.forward, transform.rotation);
    bullet.AddForce(transform.forward * bulletImpulse, ForceMode.Impulse);

但是我在此代码中有错误

无法转换类型UnityEngine.GameObject' to UnityEngine.RigidBody'

感谢您的帮助请帮助!

Instantiate方法返回GameObject,而不是RigidbodyRigidbody是该游戏对象的组件,因此要获得它,您必须致电GetComponent

GameObject gameObject = (GameObject)Instantiate(projectile, transform.position + transform.forward, transform.rotation);
Rigidbody bullet = gameObject.GetComponent<Rigidbody>();

您需要获取要使用的组件:

https://docs.unity3d.com/ScriptReference/GameObject.GetComponent.html

最终代码:

Rigidbody bullet = ((GameObject)Instantiate(projectile, transform.position + transform.forward, transform.rotation)).GetComponent<Rigidbody>();
bullet.AddForce(transform.forward * bulletImpulse, ForceMode.Impulse);

相关内容

最新更新