How can I code an animal trap that catches an animal after a certain time or catches an animal in a certain time period?
If the time is fixed and you simply want to catch the animal after X time, you can also reach for the Invoke method. It’s not as dynamic as a coroutine, but a perfectly fine option if the only thing you’re looking for is a delayed method.
private void Start() {
Invoke(nameof(CatchAnimal), 20);
}
private void CatchAnimal() {
//Catch animal code here
}
If you want to catch at a certain time then we need to delay up to that point. If you want to catch within a certain time then the probability increases during that time from 0 to 1. In either case, you can use a coroutine for this.
using System.Collections;
using UnityEngine;
public class AnimalTrap : MonoBehaviour
{
void Start()
{
StartCoroutine(WithinTime(5));
}
IEnumerator AtTime(float timer)
{
yield return new WaitForSeconds(timer);
print("Animal instantiated");
// code here to instantiate the animal
}
IEnumerator WithinTime(float timer)
{
bool animalInstantiated = false;
float startTime = Time.time;
float proportionElapsed;
while (!animalInstantiated)
{
proportionElapsed = (Time.time - startTime) / timer;
if (Random.Range(0f, 1f) <= proportionElapsed)
{
animalInstantiated = true;
print("Animal instantiated after " + proportionElapsed);
// code here to instantiate the animal
}
else
{
yield return new WaitForSeconds(1f);
}
}
}
}
You can call whichever coroutine you want (my code calls WithinTime in the Start event but try the other as well). The WithinTime coroutine checks every second (see the yield statement) but you could change that or even pass it in as a parameter.