Here’s an image of the error, and the code. The error points to the line where the enemyLaserPrefab object is instantiated (line 57 of my code). Weirdly, I changed the order of lines 50 and 51 (the ones inside if (shotCounter <= 0f) { } ), and that reduced the number of errors per enemy killed from around 35 to 1 or 2.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour
{
[Header("Enemy")]
[SerializeField] float health = 100;
[SerializeField] float shotCounter;
[SerializeField] float minTimeBtwShots = .2f;
[SerializeField] float maxTimeBtwShots = 3f;
[Header("Laser")]
[SerializeField] GameObject enemyLaserPrefab;
[SerializeField] float xLaserVel = 0f;
[SerializeField] float yLaserVel = -8f;
[Header("SFX")]
[SerializeField] AudioClip enemyExplosionSFX;
[SerializeField] [Range(0,1)] float enemyExplosionVolume = 0.75f;
[SerializeField] AudioClip enemyLaserSFX;
[SerializeField] [Range(0, 1)] float enemyLaserVolume = 0.75f;
[Header("VFX")]
[SerializeField] GameObject explosionStarsPrefab;
[SerializeField] float durationOfExplosion = 2f;
// Start is called before the first frame update
void Start()
{
shotCounter = Random.Range(minTimeBtwShots, maxTimeBtwShots);
}
// Update is called once per frame
void Update()
{
CountDownAndShoot();
}
private void CountDownAndShoot()
{
shotCounter -= Time.deltaTime;
if (shotCounter <= 0f)
{
shotCounter = Random.Range(minTimeBtwShots, maxTimeBtwShots); // Placing this line here (instead of in line 51) highly reduces the number of errors per enemy killed (?)
EnemyShot();
}
}
private void EnemyShot()
{
GameObject oneEnemyLaser = Instantiate(enemyLaserPrefab, transform.position, Quaternion.identity) as GameObject;
oneEnemyLaser.GetComponent<Rigidbody2D>().velocity = new Vector2(xLaserVel, yLaserVel);
AudioSource.PlayClipAtPoint(enemyLaserSFX, Camera.main.transform.position, enemyLaserVolume);
}
private void OnTriggerEnter2D(Collider2D other)
{
DamageDealer damageDealer = other.gameObject.GetComponent<DamageDealer>();
if (!damageDealer) { return; } //if damageDealer doesn't exist, exit the process
ProcessHit(damageDealer);
}
private void ProcessHit(DamageDealer damageDealer)
{
health -= damageDealer.GetDamage();
damageDealer.Hit();
if (health <= 0)
{
ProcessEnemyDeath();
}
}
private void ProcessEnemyDeath()
{
Destroy(gameObject);
GameObject oneExplosion = Instantiate(explosionStarsPrefab, transform.position, transform.rotation);
Destroy(oneExplosion, durationOfExplosion);
AudioSource.PlayClipAtPoint(enemyExplosionSFX, Camera.main.transform.position, enemyExplosionVolume);
}
}