我有一些错误!
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
,而不是Rigidbody
。Rigidbody
是该游戏对象的组件,因此要获得它,您必须致电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);