I keep getting the error “NullReferenceException: Object reference not set to an instance of an object EnemyStats.OnDestroy () (at Assets/Scripts/Enemy/EnemyStats.cs:68)” when clicking the Done button when trying to return to the menu. (Line 68 is “EnemySpawner es = FindObjectOfType<EnemySpawner>();”
public class EnemyStats : MonoBehaviour
{
public EnemyScriptableObject enemyData;
//Current stats
[HideInInspector]
public float currentMoveSpeed;
[HideInInspector]
public float currentHealth;
[HideInInspector]
public float currentDamage;
public float despawnDistance = 20f;
Transform player;
void Awake()
{
currentMoveSpeed = enemyData.MoveSpeed;
currentHealth = enemyData.MaxHealth;
currentDamage = enemyData.Damage;
}
void Start()
{
player = FindObjectOfType<PlayerStats>().transform;
}
void Update()
{
if (Vector2.Distance(transform.position, player.position) >= despawnDistance)
{
ReturnEnemy();
}
}
public void TakeDamage(float dmg)
{
currentHealth -= dmg;
if (currentHealth <= 0)
{
Kill();
}
}
public void Kill()
{
Destroy(gameObject);
}
private void OnCollisionStay2D(Collision2D collision)
{
//references the script from collided collider and deal damage using TakeDamage()
if (collision.gameObject.CompareTag("Player"))
{
PlayerStats player = collision.gameObject.GetComponent<PlayerStats>();
player.TakeDamage(currentDamage); //make sure to use currentDamage instead of weaponData.damage in case any damage multipliers
}
}
private void OnDestroy()
{
EnemySpawner es = FindObjectOfType<EnemySpawner>();
es.OnEnemyKilled();
}
void ReturnEnemy()
{
//references the EnemySpawner Script
EnemySpawner es = FindObjectOfType<EnemySpawner>();
//moves the enemy to a random spawn location
transform.position = player.position + es.relativeSpawnPoints[Random.Range(0, es.relativeSpawnPoints.Count)].position;
}
}