Forum begins after the advertisement:
[Part 9] NullReferenceException error when using the Done button
Home › Forums › Video Game Tutorial Series › Creating a Rogue-like Shoot-em Up in Unity › [Part 9] NullReferenceException error when using the Done button
- This topic has 2 replies, 2 voices, and was last updated 3 months, 1 week ago by ThatOneGuy.
-
AuthorPosts
-
September 21, 2024 at 12:33 am #15869::
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>();”
<code>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; } }</code>
September 21, 2024 at 2:54 pm #15870::Guy, this happens because
OnDestroy()
fires when you change scenes, as all the enemies are deleted.In such a case, the function will not be able to find the
EnemySpawner
, soes.OnEnemyKilled()
cannot fire.just add a check so that
es.OnEnemyKilled()
only fires when an enemy spawner can be found (i.e. thees
variable is not null):private void OnDestroy() { EnemySpawner es = FindObjectOfType<EnemySpawner>(); if(es) es.OnEnemyKilled(); }
September 23, 2024 at 10:33 am #15899 -
AuthorPosts
- You must be logged in to reply to this topic.
Advertisement below: