Hey,
I want to Instantiate a bullet every 2 seconds or so but it gets called every frame even though I set an interval. What’s wrong with my code?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Tower : MonoBehaviour
{
GameObject[] enemyList;
float attackRange = 5f;
GameObject nearestEnemy;
GameObject bulletPrefab;
float attackInterval = 2f;
float nextAttack = 0f;
void Start()
{
bulletPrefab = Resources.Load<GameObject>("Prefabs/BulletPrefab");
}
void Update()
{
findNearestEnemy();
if (nextAttack <= 0)
{
nextAttack = attackInterval;
if (nearestEnemy != null)
{
if (Vector2.Distance(nearestEnemy.transform.position, transform.position) <= attackRange)
{
Instantiate(bulletPrefab, transform.position, Quaternion.identity);
nearestEnemy = null;
}
}
}
else
{
nextAttack -= Time.deltaTime;
}
}
void findNearestEnemy()
{
enemyList = GameObject.FindGameObjectsWithTag("Enemy");
if (enemyList.Length != 0)
{
float minDist = Mathf.Infinity;
foreach (var enemy in enemyList)
{
float dist = Vector2.Distance(transform.position, enemy.transform.position);
if (dist < minDist)
{
nearestEnemy = enemy;
}
}
}
}
}