Hello I am having trouble with Random.Range not working as shown in the video. I’m probably just overlooking something blindingly obvious as normal. If you have any suggestions or solutions let me know.
Here is the code I am using.
SHOOTER.CS
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Shooter : MonoBehaviour
{
[Header(“General”)]
[SerializeField] GameObject projectilePrefab;
[SerializeField] float projectileSpeed = 15f;
[SerializeField] float projectileLifeTime = 5f;
[SerializeField] float baseFiringRate = 0.3f;
[Header("AI")]
[SerializeField] float minimumFiringRate = 0.1f;
[SerializeField] float firingRateVariance = 0f;
[SerializeField] bool useAI;
[HideInInspector] public bool isFiring;
Coroutine firingCoroutine;
void Start()
{
if (useAI)
{
isFiring = true;
}
}
void Update()
{
Fire();
}
void Fire()
{
if (isFiring && firingCoroutine == null)
{
firingCoroutine = StartCoroutine(FireCountinuously());
}
else if(!isFiring && firingCoroutine != null)
{
StopCoroutine(firingCoroutine);
firingCoroutine = null;
}
}
IEnumerator FireCountinuously()
{
while (true)
{
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);
}
}
}