Reputation: 818
I am trying to invoke a shooting animation in the Update function and then wait for 0.5 seconds before spawning a 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);
}
Upvotes: 0
Views: 10908
Reputation: 20030
You're forgetting to call it as a coroutine using StartCoroutine()
.
It should be:
void Update()
{
if (Input.GetMouseButtonDown (0))
{
animator.SetTrigger("Shoot"); // Start animation
StartCoroutine(WaitAndShoot());
}
}
IEnumerator WaitAndShoot()
{
yield return new WaitForSeconds(0.5f);
Instantiate (shot, shotSpawn.transform.position,shotSpawn.transform.rotation);
}
Keep in mind that this still allows you to trigger multiple shots before the first shot has been spawned. If you want to prevent that from happening, keep track of a shot being fired or not with a boolean, and check for that in addition to your GetMouseButtonDown.
Upvotes: 10