The question is answered, right answer was accepted
Destroying an instance of a prefab not working
I have written a simple pause script that creates instances of prefabs for the buttons.
The issue is that when I toggle the menu off the instances are not being destroyed.
Here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PauseScript : MonoBehaviour {
public bool paused = false;
public GameObject pauseAlert;
public GameObject playBut;
public GameObject retryBut;
public GameObject closeBut;
private GameObject pauseInst;
private GameObject playInst;
private GameObject retryInst;
private GameObject closeInst;
// Update is called once per frame
void Update () {
if (Input.GetKeyDown(KeyCode.Escape))
paused = togglePause();
}
bool togglePause()
{
if (Time.timeScale == 1f)
{
Time.timeScale = 0;
pauseInst = Instantiate(pauseAlert, new Vector3(0, 1, 0), transform.rotation);
playInst = Instantiate(playBut, new Vector3(1, -2, 0), transform.rotation);
retryInst = Instantiate(retryBut, new Vector3(0, -2, 0), transform.rotation);
closeInst = Instantiate(closeBut, new Vector3(-1, -2, 0), transform.rotation);
return (true);
}
else
{
Destroy(pauseInst);
Destroy(playInst);
Destroy(retryInst);
Destroy(closeInst);
Time.timeScale = 1f;
return (false);
}
}
}
Any help with this would be greatly appreciated, and thanks in advance.
i can't see an error. you sure you reach the Destroys??
looks like it should work.
Try DestroyImmediate ins$$anonymous$$d. I'm not sure it will help but it's worth trying.
As hexagonius says, make sure your code is getting to the else block by putting a Debug.Log("I'm in my else block");
in there.
Also, I'd change if (Time.timeScale == 1f)
to if (!paused)
because Time.timescale is a float and as a result it isn't a good idea to compare it to an exact number because rounding errors can cause false negatives.
Ah, I've found the issue, it was my error.
This script was working... when I press escape (as it should), but when hitting the play button, it just wasn't destroying from that script, so I'm a doink for overlooking that... xD
Sorry guys. goes back to hiding under a rock
Follow this Question
Related Questions
How to destroy GameObject if it overlaps another GameObject 2 Answers
Script won't work on duplicates/prefab copies until I delete Unity meta files 1 Answer
Why Original GameObject Destroy Clones ? 0 Answers
I need help destroying a clone on function. 1 Answer
How do i collect items without destroying or disabling the prefab? 0 Answers