Search code examples
c#timerdelaywaitunity-game-engine

How to get my shot delay to work


I was trying to learn how to do this with gamesplusjames on youtube but it's not working out too well. I'm pretty sure it's something minor but I can't figure out what it is. Basically my character aims her bow and arrow and shoots when I release the C key. But i need a delay so she doesn't shot faster than her animations can move. Can anyone tell me where I dropped the ball? I simplified my code to get rid of all the other junk that doesn't have to do with the shooting or aiming. Thanks.

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class tulMove : MonoBehaviour {

public Transform arrowSpawn;
public GameObject arrowPrefab;

private bool aim = false;
private bool shot = false;

public float shotDelay;
private float shotDelayCounter;

private Rigidbody2D rb;
private Animator anim;

void Start ()
{

    anim = GetComponent<Animator>();
    rb = GetComponent<Rigidbody2D>();

}

void Update(){

    if (!aim && Input.GetKeyDown (KeyCode.C))
    {
        aim = true;
        anim.SetTrigger ("aim");
    }

    if (aim && !shot && Input.GetKeyUp (KeyCode.C)) 
    {

        shot = true;
        aim = false;
        anim.SetTrigger ("shot");
        Instantiate (arrowPrefab, arrowSpawn.position, arrowSpawn.rotation);
        shotDelayCounter = shotDelay;
    }

    if (aim && !shot && Input.GetKeyUp (KeyCode.C)) 
    {
        shotDelayCounter -= Time.deltaTime;

        if (shotDelayCounter <= 0) 
        {
            shotDelayCounter = shotDelay;
            shot = true;
            aim = false;
            anim.SetTrigger ("shot");
            Instantiate (arrowPrefab, arrowSpawn.position, arrowSpawn.rotation);
             }
        }
    }
}

Solution

  • The way your code is structured right now, the shotDelayCounter only gets called when its if statement is true and it looks like that is not true all the time. Move the shotDelayCounter -= Time.deltaTime; outside of the if statement so it will be called each frame. Something like:

    shotDelayCounter -= Time.deltaTime;
    
    if (aim && !shot && Input.GetKeyUp (KeyCode.C) && shotDelayCounter <= 0) 
    {
        shotDelayCounter = shotDelay;
        shot = true;
        aim = false;
        anim.SetTrigger ("shot");
        Instantiate (arrowPrefab, arrowSpawn.position, arrowSpawn.rotation);
    }
    

    Now your counter should be working correctly as it will always be called