Unable to access instantiated GameObject within else statement
I'm building a simple spaceship 2D shooting game and built a reflector prefab which reflects the incoming missiles/lasers back at the enemies. The reflector works great, and I added some code to instantiate the shield GameObject when the 'S' button is pressed. The instantiation itself works fine, but I'm not able to find a way to smoothly destroy it after the 'S' button is pressed again. The purpose is to be able to "toggle" the Reflector on and off.
However, I'm not able to access the newly instantiated GameObject outside of the if() statement. The answer is probably stupidly easy but I can't figure out why it's not accessible. If I copy the Destroy() statement to within the if() statement, it's accessible, but I don't know why it's not outside of that.
Any help would be greatly appreciated.
Here's the code:
public class playership : MonoBehaviour {
private bool reflectorActive = false; //initialize the reflector to false
void Update () {
if (Input.GetKeyDown (KeyCode.S)) {
reflectorActive = !reflectorActive; // toggle the boolean
if (reflectorActive) {
//instantiate a new Reflector GameObject using prefab.
GameObject newReflector = Instantiate (Reflector, transform.position, Quaternion.identity) as GameObject;
newReflector.transform.SetParent (this.transform);
} else {
// destroy the reflector after it's toggled off
Destroy (newReflector);
}
}
}
}
Answer by WitchLake · Sep 28, 2017 at 11:39 AM
Try to save the gameobject as private value of your class:
public class playership : MonoBehaviour {
private bool reflectorActive = false; //initialize the reflector to false
private GameObject reflector;
void Update () {
if (Input.GetKeyDown (KeyCode.S)) {
reflectorActive = !reflectorActive; // toggle the boolean
if (reflectorActive) {
//instantiate a new Reflector GameObject using prefab.
GameObject newReflector = Instantiate (Reflector, transform.position, Quaternion.identity) as GameObject;
//saves the newly created reflector
reflector = newReflector;
newReflector.transform.SetParent (this.transform);
} else {
// destroy the reflector after it's toggled off
Destroy (reflector);
}
}
}
}
That is now working, thanks! I'm not sure I understand why though, so it would be great if someone could explain it. I'm guessing that instantiating the newReflector GameObject doesn't automatically make it accessible within this class? If so, where is it with regards to Scope?
If it's a problem of scope, is there anything that can be added to the Instantiate line that automatically scopes it properly given the current class?
GameObject newReflector = Instantiate (Reflector, transform.position, Quaternion.identity) as GameObject;
Thanks for the help!