- Home /
The question is answered, right answer was accepted
Yet another null reference exception
I have two identical instantiated objects in the game world. They both have the same script in them, and when they collide they both fire off the same error.
void OnTriggerEnter(Collider other)
{
colliderList.Add(other.gameObject);
}
void OnTriggerExit(Collider other)
{
colliderList.Remove(other.gameObject);
}
NullReferenceException: Object reference not set to an instance of an object objectCollision.OnTriggerExit (UnityEngine.Collider other)
I need to track(and sometimes modify) each objects colliders, so what am I doing wrong here?
That depends on what colliderList
is. It is probably null, therefore the null Reference Exception
Well yes, it IS null, because it's initially empty. Hence the add/remove functions. The error specifies that (UnityEngine.Collider other)is what throwing the error so I don't think the list is the problem here.
Its obvious I'm referring to the colliding objects wrong. I assumed the collider in the enter/exit functions will return me the objects, but apparently that's not so...
A null list is not the same as an empty list. An empty list is not null. Create your list.
Ah. Looks like I need to redefine my conceptions of what null is. Ray, convert to answer please, your comment made me understand.
You don't accept answers by writing "solved" in the title, you use the check mark so they are actually marked as accepted.
Answer by flamy · Jun 29, 2013 at 02:45 PM
Add this to the Start or Awake or OnEnable function of the class.
colliderList = new List<GameObject>();
This is needed because, an object needs to be initialized before being used.
and for OnTriggerExit()
void OnTriggerExit(Collider other)
{
if(colliderList.Contains(other.gameObject))
colliderList.Remove(other.gameObject);
}
This needed because you might have removed the object from list elsewhere in the code or would do that in future. It is safe to check for it always.
I already have the answer, but your tip gets you a thumbs up :) Thanks!
You should still mark this answer as accepted, so that people know this has been resolved. This does happen to be something you left out in your code, and this is why your code wasn't working. Especially considering you say you have the answer, but didn't post the answer, so this question remains open.
Another person gave me the answer first in the comments above, I asked him to convert it into an answer so I can credit him properly. Read before posting.
Close the question if you don't want to accept the answer. I do read before posting. I read your question, all the comments, and this answer, which is legit. Accept the answer, or close your question.
@Em3rgency, thanks for being thoughtful. Just please mark flamy's answer, $$anonymous$$e was not an answer it was a comment. The rules are the rules :-). Just glad to help.