- Home /
Odd NullReferenceException error. Help appreciated
I'm having problems with a null reference error that seems to be stemming from this condition: if(closestInteractable !== null)
The exact error is NullReferenceException: Object reference not set to an instance of an object.
I'm not sure why it thinks it doesn't have an object tied to it, as after coming back from the FindClosestInteractable call the print statement says that it is an Interactable.
Any help would be appreciated.
private var sceneInteractables : Interactable[]; private var closestInteractable : Interactable; private var guiEnabled = false; private var interactKey = "k"; var interactDistance = 10;
var textOffset : Vector2;
function Awake() { sceneInteractables = GameObject.FindObjectsOfType(Interactable); closestInteractable = null; //guiEnabled = false; print("Size of interactable array is " + sceneInteractables.length); }
function Update () { closestInteractable = FindClosestInteractable();
//print(closestInteractable);
if(closestInteractable !== null) {
//print("if statement is true");
guiEnabled = true;
}
else {
guiEnabled = false;
}
if(Event.current.type == EventType.keyDown && Event.current.character == interactKey && closestInteractable != null)
{
closestInteractable.Interact();
}
}
function FindClosestInteractable () : Interactable { var closest : Interactable; closest = null; var distance = Mathf.Infinity; var position = transform.position; // Iterate through them and find the closest one for (var interactable : Interactable in sceneInteractables) { var diff = (interactable.transform.position - position); var curDistance = diff.sqrMagnitude; if (curDistance < distance && curDistance < interactDistance) { closest = interactable; distance = curDistance; } } print(closest); return closest; }
function OnGui() { if(! guiEnabled) return;
GUI.Label(Rect(textOffset.x, textOffset.y, closestInteractable.InteractString.length * 10, 10), closestInteractable.InteractString);
}
I've fixed the problem. Using Event ins$$anonymous$$d of Input is a bad idea inside of the Update function. Also there were several other fun errors scattered about.
Answer by duck · Feb 21, 2010 at 07:08 AM
The only thing I can see wrong with your code is that you have !== when you should have !=.
Perhaps this causing the problem (although I'm not sure what !== does, and why it's not throwing a parsing error itself).
Your answer
Follow this Question
Related Questions
Why am I getting NullReferenceException on my .Contains()? 1 Answer
Null Reference exception help 2 Answers
Calling 'AddItem' Method giving me error NullReferenceException: 0 Answers
[Closed]NullReferenceException on Object Instantiation onto game world 2 Answers
Error after importing assets (Survival Shooter tutorial), Win32Exception 0 Answers