- Home /
Help needed with WaitForSeconds()
I am trying to invoke a shooting animation in the Update function and then wait for 0.5 seconds before spawning the laser shot. The below code isn't working for me. What can I do to achieve the desired result?
void Update()
{
if (Input.GetMouseButtonDown (0))
{
animator.SetTrigger("Shoot"); // Start animation
WaitAndShoot();
}
}
IEnumerator WaitAndShoot()
{
yield return new WaitForSeconds(0.5f);
Instantiate (shot, shotSpawn.transform.position,shotSpawn.transform.rotation);
}
Answer by looMeenin · May 04, 2014 at 06:40 PM
I didn't realize you have to call a coroutine like this:
void Update()
{
if (Input.GetMouseButtonDown (0))
{
animator.SetTrigger("Shoot"); // Start animation
StartCoroutine(WaitAndShoot());
}
}
Answer by Malarhak · May 04, 2014 at 06:54 PM
Disclaimer: I'm no expert at Unity
Honestly, WaitForSeconds should be avoided when possible. It's not really the greatest thing to use timed functions when running a synchronous loop program (a game).
What I'd do:
On mouse button down, store the date of the input lastShot = Time.time
Mark a boolean as true, meaning you want to shoot shooting = true
In update, if the boolean is true, check if Time.time - lastShot > 0.5f
If so, do your thing and mark the shooting
boolean as false
Example :
public Transform shotSpawn;
public Transform shot;
public float shootTimer = 0.5f;
private bool shooting = false;
private float lastShoot;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonDown(0)) {
shooting = true;
lastShoot = Time.time;
}
if (shooting) {
if (Time.time - lastShoot > shootTimer) {
Instantiate (shot, shotSpawn.transform.position,shotSpawn.transform.rotation);
}
}
}
why is coroutine bad? Ok it is an object so it creates garbage but it is easy to use and allows to $$anonymous$$imize the amount of variables and checks in update.
See your shooting may happen only once in the game but the check is about to happen each frame. In the end, you are about to get hundreds of check with a variable for each when you can clear it all and use some coroutines and events.
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Multiple Cars not working 1 Answer
Loop Coroutine For A Demo Mode 1 Answer
Trigger player movement on touch 1 Answer
Error Coroutine couldn't be started! 3 Answers