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 set a breakpoint in the debugger and see what's coming back from the 'find'. If it's truly empty, you must have mistagged them somehow. Perhaps 'enemy' vs 'Enemy' ?
– DaveAThere is nothing coming back from the find, but everything is correctly tagged. I even went into the enemy controller script and put: gameObject.tag = "Enemy"; in the update function so it would assign the correct tag every frame and it still isn't working.
– KingCrizzoJust curious here, what is 'Target'?
– zannghastSorry, meant to reply earlier. Target is each iteration through the targets array. It starts with a capital T because target is a keyword. Probably could be better named, but I just copied it from the example.
– KingCrizzo