- Home /
Using Coroutine rather than Update to Check Whether Time Passed
Hey,
I am wanting to create a Debug.Log to inform me when it is possible to fire a player's weapon again. I have tried
if (nextFire < Time.time)
Debug.Log ("CAN FIRE");
with nextFire being Time.time + a set amount each time the player fires a weapon. I have tried putting the above code in Update() but that simply constantly calls Debug.Log until it cannot fire.
I have read that a coroutine may be better in this instance to deal with time but only call something once rather than every frame as Update() does but I'm unsure as to how to go about this.
Any help would be greatly appreciated.
Answer by highpockets · Nov 26, 2013 at 07:48 PM
You can make a couple bools and check if the coroutine is running. like this:
var canFire : bool = true
var projectile : GameObject;
var waiting : bool = false;
function Update ()
{
if (Input.GetButtonDown ("Fire1") && canFire)
{
Instantiate (projectile, transform.position, transform.rotation);
canFire = false;
}
if ( !canFire && !waiting )
{
waiting = true;
StartCoroutine(WaitAndPrint(2.0));
}
}
function WaitAndPrint (waitTime : float)
{
yield WaitForSeconds (waitTime);
print ("Can Fire");
waiting = false;
canFire = true;
}
I haven't tested the code, but it should do the trick
Thanks, this seems like a much easier way to do things than I was before!
Your answer
Follow this Question
Related Questions
Coroutine not working properly on Android (C#) 0 Answers
Coroutines and if statements 1 Answer
How to slow down large code? 1 Answer
void update working under conditions 1 Answer