- Home /
Can I Ignore Null Reference Exceptions? ( bug? )
I'm getting an odd problem here, i won't post my code because its giantic and it really doesnt matter, but, i have two codes that are exactly the same logic and all, and what they do, is to turn off certain gameobjects. the first one works great, it turn offs the objects i want, ( using that SetActive thing ), but the other one, it does work exactly like the first one, but every time it desactive a gameobject, it says NullReferenceException, like it was trying to find the object after destroyed it or something... but the script continues to work fine. I don't know if you guys got it, but what's happening is that, both scripts works fine and iddentically, but one of them fill my console with null reference exceptions... i want to know if it is a real problem, or if i can ignore it. I had this problem with other script long ago, and i remember to just restarting unity and everything returned normal, but not this time. Well, that's it... hope you guys can awser me... (sorry for my bad english)
Answer by bkachmar · Sep 09, 2017 at 09:34 AM
I had a similar problem and in my case it turned out that I'm disabling the whole gameOblect, but keep reference to the script.
When I switched to keeping references to gameObject this disappeared.
Hope this will help.
Answer by tormentoarmagedoom · Sep 09, 2017 at 11:04 AM
You should use
if(GameObject != null)
{
}
So if the thing you want to modify does not exist, is never called so no more Null Reference Exceptions
Answer by Pangamini · Sep 09, 2017 at 03:46 PM
Short answer: Don't ignore it
Unhandled exceptions from MonoBehaviour message calls (such as Update, OnEnable, Start etc) are caught by Unity so your game doesn't crash. However, such exceptions terminate the current call stack (up to the handling point which is before unity call to your code). This means your method call is left unfinished and may lead to unpredictable behaviour. Also, having exceptions logged in the console every update really beats down the performance. Ideally, you should never have exceptions printed in the console (either avoid them or handle them yourself). However, Unity does help a lot by making references to destroyed UnityEngine.Object instances appear to be null (they are not really null, it's just how their operators are overloaded) so all you need to do is check if it's null or not.
Your answer
Follow this Question
Related Questions
Unity null check 1 Answer
iTween nullref error. Hashtable syntax problem? Not sure. 3 Answers
Unexplanable NullReferenceException Error 2 Answers
Why am I getting NullReferenceException on my .Contains()? 1 Answer
Getting error on instatiating. 0 Answers