Parsa Alemi Parsa Alemi -4 years ago 325
C# Question

Cannot convert type `UnityEngine.GameObject' to `UnityEngine.Rigidbody'

I've some Error!

Unity 3D

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

But I've error in this code

Cannot convert type
UnityEngine.GameObject' to

thank for your help
Please Help !

Answer Source

The Instantiate method returns a GameObject, not a Rigidbody. Rigidbody is a component of that game object, so to get it, you have to call GetComponent:

GameObject gameObject = (GameObject)Instantiate(projectile, transform.position + transform.forward, transform.rotation);
Rigidbody bullet = gameObject.GetComponent<Rigidbody>();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download