Instantiate error (48722)

Ive done this before but why its not working I dont know, and its getting annoying. Im trying to instantiate another bullet except this time, errors are poping up in the call itself! Heres my script:

#pragma strict

public var bullet : Transform;
public var fireRate : float = 0.5;
public var Clipsize : int = 30;
private var nextFire : float = 0.0;

function Update() 
{
 if(Input.GetButtonDown("Fire1"))
 {
 var clone : Transform = Instantiate(bullet, gameObject.Find("spawn_Point").transform.position, Quaternion.identity);
 clone.rigidbody.AddForce(transform.forward * 200);
 }
}

The things that keep happening are the Bullet will not have any force added to it, even though Ive done that in the script. It does have a rigidbody and everything and it just floats there. The error that pops up is ‘Cannot cast from source type to destination type’, which im assuming is a compiler glitch. Ive done this a million times before the same way. Why would these outcomes happen just now?

3 Answers

3

“it just floats there” you say, that does not sound like a rigidbody behaviour.

You could try to use:

var clone : Transform = Instantiate(bullet, gameObject.Find("spawn_Point").transform.position, Quaternion.identity);
if(!clone.rigidbody)
  clone.AddComponent(Rigidbody);
clone.rigidbody.AddForce(transform.forward * 200);

Try GameObject.Find instead of gameObject.Find. It is a class method not an instance method.

Split your code into several lines of code and add some checks:

var spawnPoint : GameObject = GameObject.Find("spawn_Point");
if (spawnPoint)
{
    var clone : Transform = Instantiate(bullet, spawnPoint.transform.position, Quaternion.identity);
    if(!clone.rigidbody)
        clone.AddComponent(Rigidbody);
    clone.rigidbody.AddForce(transform.forward * 200);
}

I actually went and translated it over to C#. Its working fine now. Thanks for the contributions guys.