I am making a game where enemies chase their target by moving towards them and rotating their gun towards them, but whenever the player is destroyed I get this error:
MissingReferenceException: The object of type ‘Transform’ has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
This is the rotate gun script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class rotateEnemyGun : MonoBehaviour
{
public float offset;
public Transform player;
// Update is called once per frame
void Update()
{
if (player != null)
{
Vector2 playerPos = player.transform.position;
Vector2 lookPos = playerPos - (Vector2)transform.position;
float rotZ = Mathf.Atan2(lookPos.y, lookPos.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(rotZ - offset, Vector3.forward);
}
}
}