- Home /
How do I Stop a Function ?
How so I stop a function from running? I have a script that calls a custom function when the player enters a trigger but I can't get it to stop when the player leaves the trigger?
#pragma strict
var boulder01 : GameObject;
var BoulderSpawn01 : Transform;
function OnTriggerEnter ()
{
SpawnBoulder(); //Call new function
}
function SpawnBoulder ()
{
for (var x = 1; x < 2; x++) //Set max limit of spawns
{
yield WaitForSeconds (5);
Instantiate(boulder01, BoulderSpawn01.transform.position, BoulderSpawn01.transform.rotation);
}
}
Any suggestions?
Answer by HYPERSAVV · Dec 22, 2014 at 07:20 AM
Coroutines will help you out. StartCoroutine in OnTriggerEnter, and StopCoroutine in OnTriggerExit.
Getting closer. The function/coroutine starts and stops when the player enters/exits the trigger BUT now it just spawns once, not repeatedly?
#pragma strict
var boulder01 : GameObject;
var BoulderSpawn01 : Transform;
function OnTriggerEnter ()
{
StartCoroutine("SpawnBoulder"); //Call new function
}
function SpawnBoulder ()
{
for (var x = 1; x < 12; x++) //Set max limit of spawns
{
yield WaitForSeconds (5);
Instantiate(boulder01, BoulderSpawn01.transform.position, BoulderSpawn01.transform.rotation);
}
}
function OnTriggerExit ()
{
StopCoroutine("SpawnBoulder");
}
It doesn't matter what combination I set the x var or WaitForSeconds, I just get the single spawn ?
OnTriggerStay doesn't work either, I just end up with a 1000 boulders flooding the area....lol
Answer by jmgek · Dec 22, 2014 at 07:20 AM
I write in c# so this may need some work.
var boolTrueFalse = false;
function OnTriggerEnter()
{
boolTruFalse = true;
//Call anything you want here.
}
function OnTriggerExit()
{
boolTruFalse = false;
//Call anything you want here.
}
Update()
{
if(boolTrueFalse)
{
spawnBoulder();
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613174635im_/https://answers.unity.com/themes/thub/images/avi.jpg)