instantiate a Rigidbody not work for me?

Hi, I see in script reference, it do it like this – > http://unity3d.com/support/documentation/ScriptReference/Object.Instantiate.html


using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {

    public Rigidbody projectile;
    void Update() {
        if (Input.GetButtonDown("Fire1")) {
            Rigidbody clone;
            clone = Instantiate(projectile, transform.position, transform.rotation);
            clone.velocity = transform.TransformDirection(Vector3.forward * 10);
        }
    }
}

and that is my script but doesn’t work it.
the prefab have attached a Rigidbody


using UnityEngine;
using System.Collections;

public class Weapon : MonoBehaviour {
    public int power = 100;
    public int numBullets = 20;
    public int velocity = 20;
    public Rigidbody ammo;
    private Transform canon;
    
    void Start () {
        canon = transform.Find("CanonAK47");
    }

    void Update () {
        Rigidbody bullet;
        bullet =  Instantiate( ammo , transform.position,transform.rotation);
        bullet.velocity = transform.TransformDirection(Vector3.forward*velocity);
        Physics.IgnoreCollision( bullet.collider,transform.root.collider);
    }
}

And the error is that – >

Assets/MyScripts/Weapon.cs(35,17): error CS0266: Cannot implicitly convert type UnityEngine.Object' to UnityEngine.Rigidbody’. An explicit conversion exists (are you missing a cast?)

thanks for your help !!!

“An explicit conversion exists (are you missing a cast?)” - the answer is yes, you’re missing a cast.

Instantiate returns a reference of type UnityEngine.Object. You just need to cast it into a Rigidbody, the real type:

Rigidbody clone;
clone = (Rigidbody)Instantiate(projectile, transform.position, transform.rotation);

I’m not sure when the generic version of Instantiate<> was introduced (in my Unity 3.0 i think it’s not available) but it should work as well.

You can right so:

clone = (Rigidbody)Instantiate(projectile, transform.position, transform.rotation) as Rigidbody;