Null reference exception not showing for object that is null

Hello all!

I have stumbled onto a weird problem which makes it hard to debug stuff in Unity. The problem is that sometimes null reference exceptions are not shown in the console.

I have a MonoBehaviour that has a reference to a script like this:

public class Popup : MonoBehaviour
{   
    [SerializeField] protected GameObject iconContainer;
}

The reference to iconContainer is null for sure. However when calling e.g.

iconContainer.SetActive(true);

Unity does NOT print a null reference exception in the console IF you are calling “iconContainer.SetActive” when returning from a BestHttp callback like this:

ServerConnection:OnConnectionError (BestHTTP.WebSocket.WebSocket,string) (at Assets/Scripts/Server/ServerConnection.cs:155)
BestHTTP.WebSocket.OverHTTP1:OnInternalRequestCallback (BestHTTP.HTTPRequest,BestHTTP.HTTPResponse) (at Assets/Best HTTP/Source/WebSocket/Implementations/OverHTTP1.cs:193)
BestHTTP.Core.RequestEventHelper:HandleRequestStateChange (BestHTTP.Core.RequestEventInfo) (at Assets/Best HTTP/Source/Core/RequestEvents.cs:345)
BestHTTP.Core.RequestEventHelper:ProcessQueue () (at Assets/Best HTTP/Source/Core/RequestEvents.cs:224)
BestHTTP.HTTPManager:OnUpdate () (at Assets/Best HTTP/Source/HTTPManager.cs:414)

If you call “iconContainer.SetActive” from e.g. a MonoBehaviour:Start() - function, Unity will normally print a null reference exception in the console.

How can it matter from where the call is made? Why does Unity not show the error when calling from where the stack trace above shows? Can it be some local setting or some library thing?

I have tried with Unity 2019, 2020 and 2021.

That looks like another thread servicing that connection error callback. Is that the case? You cannot bang on most of the Unity API anywhere except the main thread. Usually it complains explicitly about being off-thread.

If so, you’d need to use a construct like this to marshal the action back:

Delegate queue to marshal tasks from other threads to the main thread:

1 Like

Thanks for the reply and the explanation. I am fairly sure the callback is on the main thread but I will check to be 100%.

Edit: checked and it is on main.

Found the reason. The http code had a try - catch block that caught all exceptions and thus also the null refs.

Pokemon Exception handling! Gotta catch 'em all!

#include <std_facepalm.h>

1 Like