- Home /
Use local instantiated variable outside of scope
I'm trying to make an instantiated gameobject, and using the Vector3.MoveTowards function to simulate a projectile. I want to use MoveTowards because i need it to go to a specific place. Anyway, Unity won't let me do this because if i need to instantiate in the if statement, but if its instantiated in the if statement, it has no value outside of it. Here it my script, how can i use the Vector3.MoveTowards function on the instantiated GameObject? The error i get is use of unassigned local variable `clone'
cooldown -= Time.deltaTime;
//Firing
GameObject clone;
if(Input.GetKeyDown(KeyCode.Space)){
if(cooldown <= 0){
clone = Instantiate(projectile, projectilePosition, transform.rotation) as GameObject;
clone.transform.parent = projectileParent.transform;
cooldown = 0.5F;
}
}
clone.transform.position = Vector3.MoveTowards(transform.position, projectileTarget, 1000 * Time.deltaTime);
KEEP IN MIND THIS WHOLE BLOCK OF CODE IS IN VOID UPDATE
Answer by siaran · Jun 11, 2015 at 06:07 PM
You could intitally assign a null value to your GameObject I suppose...
You'll need to check if it isn't null then in the line where you update its position...
I don't think this is the right way to go about what you are trying to do though...
Generally when you run into this sort of problem you should rethink your program's structure. (In this case, for example, why not put a script that updates the projectile's position on the projectile object?)
Answer by tanoshimi · Jun 11, 2015 at 06:08 PM
Move the GameObject clone;
to outside the Update() function.