Coroutines
Coroutines
Sometimes we need to wait some time before a specific event should happen. For instance, let's say the character should collect some objects. When the character touches the objects, they remain in scene 2 more seconds and then they disappear. For this waiting process, we use coroutines. Let's see how the code would look like.
We will do the same steps from Object Interaction. We will also use the same code, but we will upgrade it a little.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectInteraction : MonoBehaviour
{
IEnumerator DestroyObject()
{
yield return new WaitForSeconds(2.0f);
Destroy(gameObject);
}
void OnTriggerEnter(Collider other)
{
StartCoroutine(DestroyObject());
}
}
Instead of calling the Destroy function in OnTriggerEnter, we start a coroutine using StartCoroutine(<insert name of the new function here>). Then we create a new function, which has the IEnumerator type. Inside it, we need to do 2
things:- Wait the amount of time we want to wait: yield return new WaitForSeconds(2.0f);
- Do the action we want to do when the time has expired: Destroy(gameObject);
Ultima modificare: Saturday, 24 July 2021, 23:08