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.
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.