"Cannot cast from source type to destination type"- instantiating

i've seen a few questions asked that are related to this, but none work, please help me figure out my problem, I have an AI that shoots bullets, but I get the error: "Cannot cast from source type to destination type".

var projectile : Rigidbody;
var attackTimer : float = 1;
var coolDown : float = 1;

function Shoot () {

    if(attackTimer > 0)
        attackTimer -= Time.deltaTime;

    if(attackTimer < 0)
        attackTimer = 0;

    if(attackTimer == 0){
        var clone : Rigidbody;
        //this is where it shows the error...
        clone = Instantiate(projectile, transform.position, transform.rotation);
        clone.velocity = transform.TransformDirection (Vector3.forward * 10);

        attackTimer = coolDown;

Assuming you're sure that 'projectile' is not null, it appears you might have encountered an instance of the problem discussed here:


If so, as it recommends, restarting Unity should fix it. (Where by "fix" I mean that it will stop happening for now but may recur later.)

I figured it out and my problem was that I had another script which activated the shoot script, once I merged it into one script it worked perfectly

Instantiate returns type of object which is the base class for all objects. Unity - Scripting API: Object.Instantiate

I usually cast to game object then get the component, or in your case rigidbody, instead. However, to keep your code you would need to cast (Rigidbody)Instantiate().

You've got to cast it to a transform, then you can get the gameObject or any other components.

Transform g = (Transform) Instantiate(indicatorPrefab, new Vector3(0,0,0), Quaternion.identity); GameObject obj = g.gameObject; GUITexture gui = g.gameObject.GetComponent();