Null Reference Exeption harmless?
I have real situation when i get Null Reference Exeption and this not break anything in gameplay:
void OnTriggerEnter2D(Collider2D coll)
{
var tags = coll.gameObject.GetComponent<Tag_Obj>().Tags;
for (int i = 0; i < tags.Length; i++)
{
if (tags[i] == Tag_Obj.Tag.WHEEL)
{
// do staff
}
}
}
I implement my own multi tag system by simply make tag class and put here array of enum to represent tag names instead slow string that used in compareTag call. Ideally i need to check for null component Tag_Obj before access it but then i need to call Getcomponent twice! (first for check for null, second for cache reference to local variable(for perfomance reason, this way i reduce GetComponent calls)). So i consider not do null check to reduce GetComponent call to only 1 time. And skip of null check produce null reference exeption when object that have trigger collider contact with this object but not have tag component. So question: Null reference exeption harmless by itself? I mean it not do memory leaks or something bad like that?
the exception should be considered bad.
there's little performance impact to checking whether the component is null before using it, especially compared to time taken to get the component in the first place!
you shouldn't need to call GetComponent()
more than once to do this. what makes you think that you do?
void OnTriggerEnter2D(Collider2D coll)
{
if (coll.gameObject.GetComponent<Tag_Obj>() != null) // 1 call
{
var tags = coll.gameObject.GetComponent<Tag_Obj>().Tags; // 2 call
for (int i = 0; i < tags.Length; i++)
{
if (tags[i] == Tag_Obj.Tag.WHEEL)
{
// do staff
}
}
}
}
Answer by gjf · Apr 23, 2016 at 11:59 PM
why not this?
void OnTriggerEnter2D(Collider2D coll)
{
var tag = coll.gameObject.GetComponent<Tag_Obj>();
if (tag != null)
{
var tags = tag.Tags;
for (int i = 0; i < tags.Length; i++)
{
if (tags[i] == Tag_Obj.Tag.WHEEL)
{
// do stuff
}
}
}
}
Answer by Owen-Reynolds · Apr 24, 2016 at 02:28 AM
When make the real game -- build for PC, etc... , a Null Reference Exception will crash it.
When you run in the Editor, it keeps running after a NullRefE just to help you test better. But that's just an extra editor-only thing.
Your answer
Follow this Question
Related Questions
NullReferenceException: Object reference not ... ( Assistance please ) 2 Answers
NullReferenceException: Object reference not set to an instance of an object 3 Answers
Custom class instance always return null 1 Answer
null reference help. i fundamentally dont understand. 1 Answer
why does a line renderer cause a nullreference excepetion? 0 Answers