Hi there,
I’ve tried to find a solution to my issue here but I guess I am out of luck.
Here is my shooter code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Shooter : MonoBehaviour
{
[Header("General")]
[SerializeField] GameObject projectilePrefab;
[SerializeField] float projectileSpeed = 10f;
[SerializeField] float projectileLifetime = 5f;
[SerializeField] float baseFiringRate = 0.2f;
[Header("AI")]
[SerializeField] bool useAI;
[SerializeField] float firingRateVariance = 0f;
[SerializeField] float minimumFiringRate = 0.1f;
[HideInInspector] public bool isFiring;
Coroutine firingCoroutine;
void Start()
{
if(useAI)
{
isFiring = true;
}
}
void Update()
{
Fire();
}
void Fire()
{
if (isFiring && firingCoroutine == null)
{
firingCoroutine = StartCoroutine(FireContinuosly());
}
else if (!isFiring && firingCoroutine != null)
{
StopCoroutine(firingCoroutine);
firingCoroutine = null;
}
}
IEnumerator FireContinuosly()
{
GameObject instance = Instantiate(projectilePrefab, transform.position, Quaternion.identity);
Rigidbody2D rb = instance.GetComponent<Rigidbody2D>();
if (rb != null)
{
rb.velocity = transform.up * projectileSpeed;
}
Destroy(instance, projectileLifetime);
float timeToNextProjectile = Random.Range(baseFiringRate - firingRateVariance, baseFiringRate + firingRateVariance);
timeToNextProjectile = Mathf.Clamp(timeToNextProjectile, minimumFiringRate, float.MaxValue);
yield return new WaitForSeconds(timeToNextProjectile);
}
}
I am not getting any compiler errors but enemies’ shooting is not random at all all of the enemies shoots a single projectile on the first frame and does not shoot again. Do you have any idea about what I am missing here?