Find vs. Null Reference Exception

Hi there–I’m pretty new to all this, got a little issue here, not sure if it’s something small I’m doing wrong or something more structural. Would love any help.

So, when my playerController dies, the playerController object gets destroyed, and a few seconds later, gets respawned in the center of the stage. When it gets destroyed, other objects–enemies–lose the reference to it.

For the few seconds that it’s missing, that’s not a problem for me. This is an old-school arcade type game, so if enemies that normally track you just kind of drift on their paths for a little while, that’s kind of part of the whole vibe.

The issue is trying to re-find the playerController when it respawns. Here’s the code I’m using, in my enemy script:

if (!playerController)
	{	
		playerController = GameObject.Find("PlayerController").GetComponent(PlayerController); // make sure it finds you if you've died
 	}

So, this actually works–once the playerController object respawns, the enemy figures it out, finds the reference, and goes on its merry way chasing you around.

The problem is in the interim, that line (“playerController = GameObject.Find” [etc]) throws a Null Reference Exception every frame, and makes other things in the script stop happening that shouldn’t be affected.

Is there a simple way to fix this, or is it something larger, like I shouldn’t be destroying the playerController at all or something?

Any help much appreciated–thanks!

I believe it’s a pretty simple fix.

You need to separate the two calls…

if (!playerController)
{  
       GameObject tempPlayer = GameObject.Find("PlayerController");
       if(tempPlayer !=null)
       {              
           playerController = tempPlayer.GetComponent(PlayerController);//make sure it finds you if you've died
       }
}

The reason being is, in your code, it will try to get the PlayerController Script, whether the player object has been found or not.