Conflict between Pathfinding & Respawning

Hi all,

I’m currently developing my first Unity project, in 2D, and I’m running into a little problem. I have a script (thanks, Brackeys!) that detects when the player has fallen to their death, which respawns them after a set amount of time. I also have an enemy, with an A* pathfinding script that has a variable called TARGET, and uses this to plot the enemy’s pathfinding towards the player. The conflict, however, arises between these two scripts - the respawn script is only called after the player object has been destroyed, and Instantiates a new player object at the spawnPoint - but then the pathfinding script bugs out, because the Player it was trying to path to has been deleted!

So, how exactly does one go about re-setting TARGET in the pathfinding script when the respawn script Instantiates a new player?

Thanks for your help.

I suggest this little workaround: Beside the target variable, have another “backup” variable called targetPos which holds a Vector3. When the Player (the target) is destroyed, the targetPos is assigned the player’t positions just before he dies.

In the AI script, whenever you try to access the target variable to get it’s transform.position, you also check if target isn’t null (because the object has been destroyed)., and if it is, then you use the targetPos variable instead to determine where the AI should move to.

This has the added benefit of letting your AI characters move to any Vector3 position in the world, not only to an object’s transform.position. So you can make patrol paths or random movement just by assigning the targetPos variable instead.

I would even go so far and think about if you can eliminate the target variable altogether and only use Vector3s for pathing targets.

If u have only one player u can try to find with tag in Update or make some conditions for finding it. For ex in pathfinding script. Also u need to send “dead” bool to this script before destroing player, and then bump find new object.

private var playerObj : GameObject;
private var bump : boolean;

function Start (){
	playerObj = GameObject.FindGameObjectWithTag("Player");

function Update(){
	var playerScr : NameOfPlayerScript = playerObj.GetComponent(NameOfPlayerScript);
	if (playerScr.dead){
		bump = true;
	else {
		bump = false;
	if (bump){
		playerObj = GameObject.FindGameObjectWithTag("Player");

More simple (but expensive) way in Update () drop this:

playerObj = GameObject.FindGameObjectWithTag("Player");

And dont forget to set tag for player :slight_smile: