I have an npc written in c#. If he sees you he starts chasing. I would like him to give up after a given amount of time of not seeing the player.
So, whenever the player is not visible, a countdown should start.
I am having extreme trouble with making the countdown, I’ve spent hours trying to do stuff with Coroutine and IENUMERATOR, and only made code that did nothing or crashed unity.
IEnumerator ChaseTimer()
{
float t = 0.0f;
while(!playerVisible && t<1)
{
t+=Time.deltaTime/timer;
yield return 0;
}
if(!playerVisible) //Stop chasing player
else //Continue chasing player
}
The while loop condition will be true as long as your enemy cannot see the player and t<1. Once the condition becomes false we check if the while loop was broken by one of the 2 scenarios: A)player is back in view B)timer was reached. I use playerVisable as the boolean for whether the enemy can see the player, timer is the amount of time you want the countdown to last.
that will make him give up chasing the player after 15 seconds.
it’s just that simple.
Your “giveUpChasing” routine might look something like this
function giveUpChasing()
{
chasingNow = false;
target = enemyHomeBase
play a sound .. 'mean robot sounds depressed'
}
nothing is simpler than using timers and setting the order of things in Unity. You just use Invoke.
Again a strange curiosity about about Unity3D is that for some reason many newcomers don’t realize the Invoke() functions exist. Never use yield, coroutines etc unless you are an advanced systems programmer.
You use Invoke constantly when making video games. For example,