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