- Home /
Trouble with destroying an instantiated prefab
Hi guys, I made a pause script. In that script I want to have my prefab (which is just a transparent png image/sprite saying pause) appear when the esc button is pressed and disappear when the escape button is pressed again.
I have everything else working to stop the game. The prefab does appear when I press pause... but it seems when I try to unpause, the prefab still remains. And when I pause again it just overlays the previous prefab.
I am still learning this whole thing, so I apologize in advance if it's something simple. Any advice on how to fix this or a better way to implement is appreciated. Thanks
PauseScript
using UnityEngine;
using System.Collections;
public class PauseScript : MonoBehaviour {
public bool CanPause;
void Start () {
CanPause = true;
}
void Update () {
if (Input.GetKeyDown (KeyCode.Escape)) {
GameObject newPause = (GameObject)Instantiate(Resources.Load("Pause"));
if(CanPause)
{
Debug.Log("pause");
Time.timeScale=0;
//GameObject Pause = (GameObject)Instantiate(Resources.Load("Pause"));
audio.pitch = Time.timeScale = 0;
CanPause = false;
}
else
{
Time.timeScale=1;
GameObject.Destroy(newPause);
audio.pitch = Time.timeScale = 1;
CanPause=true;
}
}
}
}
Answer by behzad.robot · Jul 05, 2014 at 06:26 PM
Why r u even trying to do it like this U could use gui objects in ur code instead(much better than dealing with gameobjects)and i'd never seen someone instantiating an object like that (As long as i know Usually people use a public variable!)And man i think the problem is inside the if (Input.GetKeyDown (KeyCode.Escape)) u create a new pause once the button is pressed not caring whether there is already one or not!Try Defining the Variable of newPause outside this if and Putting an instantiate of ur pause screen inside if(CanPause) :D Like this:
/ I'm not really good in c# But i think the problem is where u define this and where u put it's value nothing to do with my c# syntax knowledge/
GameObject newPause //Defining this variable as a private one outside Update :D
void Update () {
if (Input.GetKeyDown (KeyCode.Escape)) {
if(CanPause)
{
newPause = (GameObject)Instantiate(Resources.Load("Pause"));
// u c putting this here :D
Debug.Log("pause");
Time.timeScale=0;
//GameObject Pause = (GameObject)Instantiate(Resources.Load("Pause"));
audio.pitch = Time.timeScale = 0;
CanPause = false;
}
else
{
Time.timeScale=1;
GameObject.Destroy(newPause);
audio.pitch = Time.timeScale = 1;
CanPause=true;
}
}
}
Answer by pinkanna · Jul 09, 2014 at 02:16 AM
Sorry for taking so long to respond. This works. Thank you very much!