r/UnityHelp • u/fortnitemonopoly • Mar 07 '22
Player death reference issue
When my player dies the game crashes with an error saying there is a missing reference exception, The problem is coming from the script below which references the player, I have tried many solutions and I was wondering if anyone has any ideas, thank you.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyMethod : MonoBehaviour
{
[SerializeField]
private float speed = 1.5f;
[SerializeField]
private GameObject player;
public int damage;
public float distance;
public LayerMask whatIsSolid;
// Start is called before the first frame update
void Start()
{
player = GameObject.FindGameObjectWithTag("Player");
}
// Update is called once per frame
void Update()
{
Swarm();
}
private void Swarm()
{
transform.position = Vector2.MoveTowards(transform.position, player.transform.position, speed * Time.deltaTime);
RaycastHit2D hitInfo = Physics2D.Raycast(transform.position, transform.up, distance, whatIsSolid);
if (hitInfo.collider != null)
{
if (hitInfo.collider.CompareTag("Player"))
{
hitInfo.collider.GetComponent<Health2>().TakeDamage(damage);
}
}
}
}
2
u/Maniacbob Mar 07 '22
Well your Swarm() function is still getting called every frame by the Update and is using the player.transform.position as a destination. If you have destroyed or disabled the player object, which I assume that you're doing when the player dies, that position is going to be a null reference and throw your errors. Either you need to check every frame that the game is still active (ie. the player isn't dead) or as part of player death function it needs to disable your enemies from trying to move. Depends on which you want to make that reference and if you have anything else that is dependent on the state and/or storing that information.