Delay the bullet creation?

Looking for some advice/suggestions - I want to add a delay in the code, in between playing the animation & instantiating the projectile:

    private void shootAction_OnShoot(object sender, ShootAction.OnShootEventArgs e)
    {
        animatorPlayer.SetCharacterState("Cast2"); //My code looks different, as I am using other assets

        //This is where I want to add the delay

        Transform bulletProjectileTransform = 
            Instantiate(bulletProjectilePrefab, shootPointTransform.position, Quaternion.identity);

I tried using an Invoke, but that doesn’t work when you have parameters (as we do). I’m not sure if I could use this as a Coroutine, as I am still very new to coroutines.

Any suggestions?

I would use a coroutine. They’re really not that complicated, and Unity suggest you use them anyway. From the documentation for Invoke

I don’t know if you are using any of the parameters, so here’s a sample that passes them both. You can remove the ones you aren’t using

private void shootAction_OnShoot(object sender, ShootAction.OnShootEventArgs e)
{
    StartCoroutine(OnShootRoutine(sender, e));
}

private IEnumerator OnShootRoutine(object sender, ShootAction.OnShootEventArgs e)
{
    animatorPlayer.SetCharacterState("Cast2"); //My code looks different, as I am using other assets

    yield return new WaitForSeconds(2f); // <- Wait here for however long you want

    Transform bulletProjectileTransform = 
            Instantiate(bulletProjectilePrefab, shootPointTransform.position, Quaternion.identity);
    // rest of the code
}
1 Like

This is pretty much how I would handle this as well.

1 Like

This solution was absolutely perfect! Thank you so much!

For this kind of scenario is exactly why I created my simple FunctionTimer in my utilities Trigger an Action after some Time - Code Monkey
I can easily pass in an Action and trigger it after some time.

But yes that Coroutine would work just the same.

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms