Question by
lxq · Sep 21, 2015 at 01:22 AM ·
instantiatetrigger
Instantiate at Intervals when trigger
I'd like to instantiate a prefab (1) at every 2s when the player enter the trigger and (2) stop leave the trigger. But I cannot satisfy the two condition now. I am a beginner so could someone help me? Thank you.
Comment
Best Answer
Answer by Vivek-Joshi · Sep 21, 2015 at 06:55 AM
Hello, For (1) You can use
void OnTriggerEnter(Collider col)
{
InvokeRepeating ("MethodName", 0f, 2f); // It will call the method "MethodName" after 0 second at every 2 seconds interval.
}
or you can try
void OnTriggerEnter(Collider col)
{
StartCoroutine("MethodName");
}
IEnumerator MethodName()
{
yield return new WaitForSeconds (2);
StartCoroutine ("MethodName");
}
You can stop these both functions calling continuously after 2 seconds by using:
If you are using InvokeRepeating - CancelInvoke ("MethodName");
If you are using Coroutine - StopCoroutine("MethodName"); or StopAllCoroutines (); //If there is only one coroutine in the script.
Your answer
![](https://koobas.hobune.stream/wayback/20220612034453im_/https://answers.unity.com/themes/thub/images/avi.jpg)