- Home /
The question is answered, right answer was accepted
Why does if(levelToLoad ==null) not work?
I'm creating a script, here is a snippet,
var levelToLoad : String;
function Start ()
{
if(levelToLoad ==null)
{
Debug.LogError("Have You Forgotten To Fill In levelToLoad?");
}
}
So i want the editor to tell me that i forgot to fill it in if its empty, but this does not work... There is no Debug.LogError even if its empty... Thanks for any information.
Answer by fafase · Jun 13, 2013 at 05:28 PM
As opposed to the other answer you got, string can be null and should be null in C# and other language
It is a safe way to avoid crash while trying to use an non-initialized string.
// Crash
string str;
Console.WriteLine(str);
// No Crash
string str = null;
Console.WriteLine(str);
But a simple declaration does not set the string to null. You need to do it:
var levelToLoad : String = null;
function Start ()
{
if(levelToLoad ==null)
{
Debug.LogError("Have You Forgotten To Fill In levelToLoad?");
}
}
EDIT: I realized Unity does not take comparison (at least not in UnityScript) so you need to use:
if(String.IsNullOrEmpty(levelToLoad))
Even if i add levelToLoad : String = null; this does not work.. I really appreciate you information.
Ok my bad, the simple comparison does not do it in Unity !!!??? You need to use if(String.IsNullOrEmpty(levelToLoad))
IsNullOrEmpty is always the safest way. $$anonymous$$eep in $$anonymous$$d that Unity will initialize public variables automatically in the inspector which would set strings to an empty string and not to null.
A string is a reference type, but it's treated differently by the compiler and usually is never null since it acts more like a value type. You can set it explicitly to null, but the value you assign in field-initializers are overwritten by Unity when the object is deserialized at the beginning.
As general rule: Inspector-value > field-initializer-value.
So no matter what you set in the script, the inspector will overwrite it.
Answer by AntiLunchBox · Jun 13, 2013 at 05:20 PM
strings aren't supposed to be null--well atleast not in c#. if c# you would do:
if(String.IsNullOrEmpty(levelToLoad))
or
if(levelToLoad == "")
one of those will work.
Okay great! Successfully implemented if(levelToLoad == ""). Thank you for your time :) I also appreciate you explaining that Strings aren't supposed to be null.. Very helpful. Thank you! :)
fafase down below is right about strings being null, its floats and ints that can't be null.
Well, it's even possible to declare a nullable int or float, but yes, usual value types can't be null.