- Home /
How can I break out of a for loop after a trigger event
I'm trying to create a cross pattern explosion with this code, the point is that if the fire hits a wall then I want to break out of the for loop to stop more objects being created in that axis, the next loop should still execute normally, my problem is that it doesn't I know the trigger even is called because the object on top of the wall gets deleted, but the variable stat is not changed and the for loop resumes and every element is created.
public void explode(Vector3 fpos)
{
stat = true;
//x axis +
for (int i = 0; i < xplodrange + 1; i++)
{
if (stat)
{
rpos = new Vector3(fpos.x + i, 0.75f, fpos.z);
Instantiate(this, rpos, Quaternion.identity);
}
else
{
break;
}
}
stat = true;
//x axis -
for (int i = 0; i < xplodrange + 1; i++)
{
if (stat)
{
rpos = new Vector3(fpos.x - i, 0.75f, fpos.z);
Instantiate(this, rpos, Quaternion.identity);
}
else
{
break;
}
}
stat = true;
//z axis +
for (int i = 0; i < xplodrange + 1; i++)
{
if (stat)
{
rpos = new Vector3(fpos.x, 0.75f, fpos.z + i);
Instantiate(this, rpos, Quaternion.identity);
}
else
{
break;
}
}
stat = true;
//z axis -
for (int i = 0; i < xplodrange + 1; i++)
{
if (stat)
{
rpos = new Vector3(fpos.x, 0.75f, fpos.z - i);
Instantiate(this, rpos, Quaternion.identity);
}
else
{
break;
}
}
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("wall"))
{
stat = false;
Destroy(gameObject);
}
}
Answer by Maniacbob · Jan 25, 2020 at 11:59 PM
Based on what I'm seeing here, your first function is all going to happen in one update meaning that it is unlikely verging on impossible for your stat variable to trip in the middle and cut off your instantiation calls. Unless this is a function being called repeatedly and regularly in which case this is never going to work because the first thing that the function does is set the variable back to true.
From my understanding what you want to do is spawn objects regularly until your trigger turns it off. What I would do is convert your spawning function into a coroutine with a while loop that while the trigger is on and the count is under a certain number keeps spawning objects. Store the co-routine in a variable so that you can start it, and then when your trigger is tripped it calls a stop co-routine on the object and then destroys it.
See the links for starting and stopping coroutines.