Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Making a rate of fire.

Discussion in 'Scripting' started by dr_mailman, Feb 10, 2016.

  1. dr_mailman

    dr_mailman

    Joined:
    Jan 8, 2016
    Posts:
    16
    I am currently working on a script for the enemy to shoot instantiated bullet prefabs at me, I have everything working well except being able to set a rate of fire on my script, i am trying to use a waitforseconds function but i dont think i am doing it properly and need pointing in the right direction.

    The code is supposed to wait 5 seconds between each shot.

    thanks for any help.

    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. public class EnemyShootingScript : MonoBehaviour {
    6.   public bool ShootAtPlayer = false;
    7.   public Transform barrelEnd;
    8.   public Rigidbody Bullet;
    9.   public float bulletSpeed;
    10.   public Animation Recoil;
    11.   public bool allowFire;
    12.  
    13.   // Use this for initialization
    14.   void Start () {
    15.    
    16.    }
    17.    
    18.    // Update is called once per frame
    19.    void Update () {
    20.   if (ShootAtPlayer&&allowFire)
    21.   {
    22.   allowFire = false;
    23.   Instantiate(Bullet, barrelEnd.position, barrelEnd.rotation);
    24.   GetComponent<Animation>().Play("Recoil");
    25.   GetComponent<AudioSource>().Play();
    26.   new WaitForSeconds(5);
    27.   allowFire = true;
    28.   }
    29.    
    30.    }
    31.  
    32.   void OnTriggerEnter(Collider other)
    33.   {
    34.   if (other.CompareTag("Player"))
    35.   ShootAtPlayer = true;
    36.   }
    37. }[code]
     
  2. Hyblademin

    Hyblademin

    Joined:
    Oct 14, 2013
    Posts:
    725
    Try using a timer variable to keep track of how much time has passed between shots.

    Code (CSharp):
    1. public float shotTimer;
    2. public float shotPeriod;     //Assuming this is set to 5 in inspector
    3.  
    4. ...
    5.  
    6. if (shotTimer = 0)     //If there is no shot cooldown...
    7. {
    8.      //Perform firing actions
    9.      Instantiate(Bullet, barrelEnd.position, barrelEnd.rotation);
    10.      GetComponent<Animation>().[URL='http://unity3d.com/support/documentation/ScriptReference/30_search.html?q=Play']Play[/URL]("Recoil");
    11.      GetComponent<AudioSource>().[URL='http://unity3d.com/support/documentation/ScriptReference/30_search.html?q=Play']Play[/URL]();
    12.    
    13.      shotTimer = shotPeriod;
    14.    
    15. }
    16.  
    17. if (shotTimer > 0)     //If there is a shot cooldown...
    18. {
    19.      shotTimer -= Time.deltaTime;     //Subtract time since last frame from timer
    20.      shotTimer = Mathf.Max(shotTimer, 0);     //If timer is less than 0, return 0
    21. }
    22.