- Home /
Trying to not make an infinite loop
I'm trying to make it so that when the player presses the space bar, the already existing field of asteroids is deleted, and replaced with another. The duplicateMe(); command makes the field of asteroids, but I'm having trouble with the Destroy(); command. When I press space, it destroys the field and makes another field, but the more I press space, the more asteroids spawn exponentially.
if (Input.GetKeyDown(KeyCode.Space))
{
Destroy(newObj);
cloneThis = true;
duplicateMe();
}
duplicateMe(); code if you need it:
public void duplicateMe()
{
// makes sure this only runs on the original meteor
if (cloneThis == true)
{
int amountOfClones = Random.Range(1, 3);
// makes a random amount of meteors in random positions
for (i = 0; i < amountOfClones; i++)
{
transform.position = new Vector2(Random.Range(0, 4), Random.Range(0, 4));
newObj = Instantiate(self);
newObj.GetComponent<CloneMe>().cloneThis = false;
}
}
cloneThis = false;
}
First destroy all objects
Than make:
for(int i=0;i<100;i++){
Instantiate (asteroid);
}
Don't have destroy 1 in same function as creation.
Somewhere you need an list of asteroids
Like this
static List<GameObject> aster = new List<GameObject>();
You can destroy them like this:
while(aster.Count>0){
Destroy (aster[0]);
aster.RemoveAt(0);
}
and on the start
aster.Add(this);
You asked this question already and I already answered it.
Your answer
![](https://koobas.hobune.stream/wayback/20220613045951im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Generate randoms planets with a specific script 0 Answers
Extra objects keep appearing in scene view 0 Answers
Respawning gameobject 2 Answers
Game objects missing after instantiating? 1 Answer
Cannot destroy instantiated objects 2 Answers