- Home /
Enemy fire rate? help!
Hi, I can not add the rate of fire, does anyone know how to make it work? Thank you!
using UnityEngine;
using System.Collections;
public class EnemyShoot : MonoBehaviour {
public GameObject Player;
public GameObject Projectile;
public float FireRate = 0f;
private float NextTimeToFire = 0f;
void Start () {
Player = (GameObject) GameObject.FindWithTag ("Player");
}
void Update () {
GameObject clone;
NextTimeToFire = Time.time + 1f/FireRate;
clone = Instantiate(Projectile, transform.position, transform.rotation) as GameObject;
clone.transform.TransformDirection(Vector3.forward * 80);
Projectile.transform.position = Player.transform.position;
}
}
Comment
Best Answer
Answer by Hellium · Jan 13, 2019 at 06:25 PM
void Update ()
{
if( Time.time > NextTimeToFire )
Fire();
}
void Fire()
{
GameObject clone = Instantiate(Projectile, Player.transform.position, Player.transform.rotation) as GameObject;
// Not needed
// clone.transform.TransformDirection(Vector3.forward * 80);
// Projectile.transform.position = Player.transform.position;
NextTimeToFire = Time.time + FireRate;
}
Answer by sh_code · Jan 13, 2019 at 08:32 PM
Or, use coroutines. They make handling time-dependent and delayed code much easier.
Your answer
Follow this Question
Related Questions
fps shooting enemy 1 Answer
Problem with firing laser in direction of camera 1 Answer
FPS rigidbody bullets not moving to center of screen 0 Answers
Shooting and health Help 0 Answers