- Home /
NullReferenceException error
Getting a NullReferenceException error (Object reference not set to an instance of an object) at the line that starts "transform.rotation".
var targetTag:String;
var speed:float;
var acceleration:float;
var lifeDuration:float = 3.0;
var maxRotation:float;
function Update()
{
if(lifeDuration <= 0)
Destroy(gameObject);
else
{
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.LookAt(closest.transform);
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(closest.transform.position - transform.position), maxRotation * Time.deltaTime);
speed += Time.deltaTime * acceleration;
transform.position += transform.forward * speed * Time.deltaTime;
lifeDuration -= Time.deltaTime;
}
}
Answer by Blankzz · Aug 11, 2011 at 02:13 AM
I don't know if I am being blind or not but I can't see where you have defined closest?
Ah you're right, I removed that for some reason while trying to fix it. Anyways, the declaration for GameObject closest has been added back in but the original error persists. Any ideas?
Debug.Log(closest) after the for loop. If you get a null reference exception you know its something to do with your distance testing logic.
Added the debugger and it returned "Enemy(Clone) (UnityEngine.GameObject)" so it seems as though closest is defined properly
Try giving your public variables default values. I can't see anything wrong at the moment. Its late here ;)
Ah you're a genius :D It was because I forgot to define maxRotation. I set it to a value and now everything is great! Thanks for the help.
Just needed someone to think through it with me.