Need a solution to solve a null reference bug...

So I have a teleporter beam come down over your player units, and it aquires the game object it’s target it on, plays out a little bit of animation, and then if the target is still there, and if the player didn’t block it…it should beam it up.

The problem is, that if either the player blocks it at the last second, or the unit dies by other means…I’m getting a null reference error when it tries to beam up.

I’m unsure how to solve this, as it seems to be happening at the very last moment of beam up.

function BeamUpTarget ()
{
	yield WaitForSeconds (.15);								// put this in here so it doesnt accidently select a farmer before it gets to it's beam location
	myTarget.GetComponent(BeamUpFarmer).ChangeColor ();		// starts the farmer color change	
	yield WaitForSeconds (timeToWaitForBeamUp);				// waits for decided time before beam up
	
	// run a last second check to see if target has a hat on
	if (myTarget.GetComponent(BeamUpFarmer).tinFoilHat == false)
	{
		if (myTarget)
		{
			myTarget.GetComponent(BeamUpFarmer).BeamUp ();
			yield;
		}
	}
	else
	{
		if (myTarget)
		{
			myTarget.GetComponent(BeamUpFarmer).ResetColor ();
			yield;
		}
	}			
	yield;
}

The exact line that Unity is pointing me too is “if (myTarget.GetComponent(BeamUpFarmer).tinFoilHat == false)”

I’m not sure how to prevent this null error from happening as I’m doing a last second check, if the game object (myTarget) is still available.

And ideas of what I could do differently, or perhaps what I may be over looking?

Check that myTarget != null before attempting to reference it.