- Home /
Issue instantiating an object with button click
I want to fire a missile when I press on a button but the editor tells me the object has not been assigned when I'm sure it has been, the code I'm trying to use to instantiate is as follows:
public void fireMissile()
{
GUICounters.missiles--;
Rigidbody clone;
clone = Instantiate(missile, shootPoint.transform.position, shootPoint.transform.rotation) as Rigidbody;
clone.velocity = transform.TransformDirection(Vector3.forward * 200);
if (clone.gameObject.tag == "missile")
{
Destroy(clone.gameObject, 1.5f);
}
}
And this is the Inspector for my object:
As you can see, the bullet has been added and it is a rigidbody, yet when I click the button, I get the error that it has not been assigned, if anyone could help I'd appreciate it as it is driving me mad.
Is player$$anonymous$$issile linked to a prefab in the project and not a gameobject int the heirarchy?
Yeah its a prefab in the project tab, its not initially in the scene
Hey $$anonymous$$Fitz91, did your problem get solved? If yes, then can you please explain it to me as I'm facing the same problem, while doing the same thing that you were trying to do.
Answer by spunktrumpet · Sep 17, 2014 at 02:04 PM
I'm assuming the missle is a prefab, put it into a folder with the name "Resources" and change "missle" to whatever your prefab is called.
clone = Instantiate(Resources.Load("missle"), shootPoint.transform.position, shootPoint.transform.rotation) as Rigidbody;
Answer by Eudaimonium · Jun 29, 2016 at 04:49 PM
Why are you instantiating it as Rigidbody?
Instantiate as GameObject, then access rigidbody later.
At which line is the exception thrown? I am not 100% sure but if you only instantiate as rigidbody, it will not have it's .gameObject which you are trying to access in the if tag comparison.
Yeah, I guessed the same thing later on. It was solved after instantiating as a Rigidbody.