Found script for homing missiles, but can't past Null Reference error

This is a script I got off YouTube for making a homing missile. In the video it functions exactly how I want my missiles to function, so I would really like to get it to work. I keep getting a runtime error for “NullReferenceException: Object reference not set to an instance of an object”.

I know this means that the script is not finding my enemies in the game and adding them to the ‘targets’ array, because if it was then the missiles would be working as they should. So the error must be in the line “var targets : GameObject = GameObject.FindGameObjectsWithTag(“Enemy”);” though the error says it is on the “transform.rotation=Quaternion.Slerp…” line.

As far as I can tell it should be finding my enemies which are correctly tagged. Anyone have any ideas as to why the script can’t find my enemies?

var speed : float;
var turn : float;

function Update (){
	var targets : GameObject[] = GameObject.FindGameObjectsWithTag("Enemy");
	var closest : GameObject;
	var closestDist = Mathf.Infinity;
	
	for (Target in targets){
		var dist = (transform.position - Target.transform.position).sqrMagnitude;
		
		if(dist < closestDist){
			closestDist = dist;
			closest = Target;
		}
	}
	transform.rotation=Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(closest.transform.postition-transform.position),turn*Time.deltaTime);
	transform.position+=transform.forward*speed*Time.deltaTime;
}

I would check with the line that the debugger had reported the error to occur. That is:

transform.rotation=Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(closest.transform.postition-transform.position),turn*Time.deltaTime);

In this line, the parameter “closest.transform.postition” in the LookRotation method might be the cause. What could be happening is that the object referenced by ‘closest’ is being destroyed before this actual method call.

To verify this claim, you could maybe print a null check just before that very line with something like:

Debug.Log("Is closest null? " + (closest == null));

If you want to abandon this, you could set the name of each enemy to Enemy and find all objects by that name, or probably better yet, keep an List of enemy objects as they are created and manage that.