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' toUnityEngine.Rigidbody'. An explicit conversion exists (are you missing a cast?)

thanks for your help !!!!!

more ▼

asked Jun 11 '11 at 04:30 PM

juliancruz87 gravatar image

67 44 49 50

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

"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.

more ▼

answered Jun 11 '11 at 04:39 PM

Bunny83 gravatar image

66.9k 22 68 268

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here



Answers and Comments



asked: Jun 11 '11 at 04:30 PM

Seen: 2656 times

Last Updated: Jun 11 '11 at 04:42 PM