- Home /
C# Enemy shoot on timer
I've been struggling with this for days. I have finally got an enemy to spawn bullet prefabs towards a player but no matter what I try the bullets are spawning rapidly when I need them to shoot every two seconds or so. Any help would be amazing as I'm pulling my hair out here.
class EnemyAI : MonoBehaviour {
public GameObject Player;
private float ViewRange = 40;
private float RayRange = 20;
private int vel = 8;
public RaycastHit LastPos;
public Vector3 RayDirection = Vector3.zero;
public GameObject target;
public Rigidbody Bullet;
public Transform Muzzle;
public void Update()
{
RayDirection = Player.transform.position - transform.position;
if (Vector3.Angle(RayDirection, transform.forward) < ViewRange)
{
if (Physics.Raycast(transform.position, RayDirection, out LastPos, RayRange))
{
if (LastPos.collider.tag == "Player")
{
Attack();
}
}
}
}
public void Attack()
{
transform.LookAt(LastPos.transform.position);
if (RayDirection.magnitude > 10)
{
transform.position = Vector3.MoveTowards(transform.position, LastPos.transform.position, Time.deltaTime * vel);
}
else
{
Rigidbody b = GameObject.Instantiate(Bullet, Muzzle.position, Muzzle.rotation) as Rigidbody;
b.AddForce(250 * b.transform.forward);
}
}
private void OnCollisionEnter(Collision Hit)
{
}
}
Comment
Answer by Flint Silver · Apr 14, 2014 at 06:19 PM
You could create a Timer, for example a float that is reduced by Time.deltaTime, here an example (Obviously this void Attack will be called in Update, else it won't work):
private float timer = 5f;
private void Attack()
{
timer -= Time.deltaTime;
if (timer <= 0)
{
// Spawn Bullet or whatever else
}
}
Or you could use IEnumerator and StartCourotine(there are few examples in the link).
Your answer
![](https://koobas.hobune.stream/wayback/20220613142714im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Non Spammable Skill/Button 1 Answer
Shoot Delay in C# 1 Answer
keybind problem 0 Answers