Enemy follow player when respawning

I have an enemy that follows my player, but when my player dies, and respawn the enemy cant find the new player.
How can i get the enemy to fint the new pleyer prefab that spawn?

here’s my script:

using UnityEngine;
using System.Collections;

public class EnemyFollow : MonoBehaviour {

public Transform target;
public int moveSpeed;
public int rotationSpeed;
public int maxdistance;
private Transform myTransform;

void Awake()
{
	myTransform = transform;
}


void Start ()
{
	

}


void Update (){
	
	if (Vector3.Distance(target.position, myTransform.position) < maxdistance){

		Vector3 dir = target.position - myTransform.position;
		

		dir.Normalize();
		
	
		myTransform.position += dir * moveSpeed * Time.deltaTime;
	} 

}

}

Give the player a unique tag e.g. Player

Then in update do the following

if(target == null)
{
    target = GameObject.FindGameObjectWithTag("Player");
}

As long as your PreFab has that tag then each time it respawns it’ll find the player again.

You can also make target private as no need to drag the player onto it.

When the player dies, do you call Destroy on the player GameObject? That would make the target Transform null, and would probably start throwing null reference exceptions.

You’ll either need to not Destroy the player’s GameObject, or have the enemy do something like this:

    if (target == null)
    {
        GameObject player = GameObject.FindGameObjectWithTag("Player");

        if (player != null)
             target = player.transform;
    }

    else if (Vector3.Distance(target.position, myTransform.position) < maxdistance)
    {
         Vector3 dir = target.position - myTransform.position;
         dir.Normalize();
         myTransform.position += dir * moveSpeed * Time.deltaTime;
    } 

This solution would rely on the player (and only the player) GameObject being tagged as “Player”. Now if the target transform becomes null (because the player has been destroyed), enemies will attempt to find a GameObject tagged as “Player” and make it’s transform the new target, otherwise, they will do nothing.