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;
}
}
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.