- Home /
Unity null check
Ok, I'm executing this code:
_gameData.Initialize();
var mission = _gameData.Missions.ElementAt(0);
Debug.Log("Mission is: " + mission.Details.MissionText);
if (mission == null)
{
Debug.Log("Mission is null");
return;
}
Debug.Log("Mission is: " + mission.Details.MissionText);
And I get this output:
How in the world is that possible? Where's the logic? How am I supposed to make null checks now? And how will null propagation from C#6 work with this?
I would check your $$anonymous$$ission class (or its base classes) and see if the '==' operator is getting overloaded. also see if it has any implicit type conversions.
I would also recommend not using implicit types (var) until its actually needed even though it'll work. Especially since ElementAt(0) is likely not returning an anonymous type. while this is mostly to help make your code more readable, it may also be that its affecting the equality check (though unlikely).
mission might be implicitly casting to a different type, and casting to a null (typically when using the 'as' keyword)
Answer by Thex_PiedDroit · Sep 13, 2017 at 03:34 PM
I think it's probably because it goes there twice (since missions count is 2) and the second one automatically skips the Debug.Log cause it can't access Details.MissionText from a nullobject (though it should make an error i suppose, but i know sometimes it doesn't, and just randomly decides to skip code). Have you tried debugging it with breakpoints to see what exactly is happening?