Invoke shoot delay problem.

I can’t figure out how to delay my gun shoots/shooting/shots… To delay between the shots.

I’m tryong to use Invoke(“Firing”, shotDelay); and its not working.

For the AI I use InvokeRepeating and thats making it even worse lol.

This is the code in thee gun.

    public float shotDelay = 1.0f;
    
    
    void Firing(){
    
          Instantiate...bla bla, it works.
    
    
    }

// this what is invoked by the AI which then invokes the above with delay, which is not working.

void Shoot()

 Invoke("Firing", shotDelay);

}
}

… and this is inside the AI script

void Shooting(){

    weaponRifleScript.InvokeRepeating("Shoot", 0.5f, 20);
    
    // The invoke repeatings last float 20 which is invoke rate seems to have no effect.
 
}

Same problem with the player controlled Rifle too.

// 

 void Update(){
 
   if(Input.GetKeyDown(KeyCode.Mouse01))
    {
          
      
      Invoke("Firing", shotDelay)

    }


   
}

To clarify, the Invoke delay in the rifle scripts is not working. No delay is there. How do I get a good delay?

Please help me…

Thanks.

Example for player controlled Rifle:

float currTime = 0;


    void Update(){
     
       if(Input.GetKeyDown(KeyCode.Mouse01) && currTime + shootDelay < Time.time)
        {
          Invoke("Firing", shotDelay);
          currTime = Time.time;
        }

Please check my thread, I will be very thankful :slight_smile: http://forum.unity3d.com/threads/191923-Full-corse-how-to-make-a-horror-game-AVAILABLE

I’ve modified Weenchehawk’s code slightly. The following code is tested, and works.

public double shotDelay = 10;
private double endDelay = 0;
	
private int shotNumber = 0;
 
// Yes, it is supposed to be public
public void Awake()
{
    endDelay = Time.time;
}
 
public bool Recharged()
{ 
    return (Time.time > endDelay);
}

public void Shoot()
{
 
	if(Input.GetKeyDown(KeyCode.Mouse0)&& Recharged())
	{
		Debug.Log ("Shooting bullet " + shotNumber.ToString()); 
		endDelay = Time.time + shotDelay;
		shotNumber++;
	}
}
	
public void Update()
{
	Shoot();
}

You know, it’s funny. I answered this question in another thread on a very similar topic just last night (here : link text). The short version is that most compilers will optimize the sh1t out of most of your statements way better than you ever can. Human’s are better at optimizing algorithems though.

I daresay the compiled code in both is probably equally efficient but even if it weren’t there wouldn’t be much in it. Go with whatever is most readable / maintainable for yourself.