- Home /
Public variable instance of custom class is never null
Is this by design? Here's an example:
public class NullTest extends MonoBehaviour{
var foo : Bar = null;
function Update(){
print(foo);
}
public class Bar{
var parameter : int;
}
}
in this script print(foo) will print NullTest+Bar (and evaluate true if used as a boolean) with nothing assigned to its parameters in the inspector... but will evaluate Null if foo is made a private variable.
I'm trying to design an NGUI based inventory system, and in it each inventory slot is a separate sprite object with an InventorySlot script; and I want the top level panel of the GUI to have an InventoryManager that manages all the slots; I ran into this issue because InventoryManager needed to check which slots were "occupied" (if slot.item != null), but because they were all public they never were!
Is adding a "filled" boolean parameter to my InventorySlot script and making the item private pretty much my only option?
Answer by Landern · Aug 20, 2014 at 01:32 PM
This is documentated, the editor is instantiating the public field:
No support for null for custom classes
pop quiz. How many allocations are made when deserializing a MonoBehaviour that uses this script:
class Test : MonoBehaviour {
public Trouble t;
}
[Serializable]
class Trouble {
public Trouble t1;
public Trouble t2;
public Trouble t3;
}
It wouldn’t be strange to expect 1 allocation. That of the Test object. It also wouldn’t be strange to expect 2 allocations. One for the Test Object, one for a Trouble object. The correct answer is 729. The serializer does not support null. If it serializes an object, and a field is null, we just instantiate a new object of that type, and serialize that. Obviously this could lead to infinite cycles, so we have a relatively magical depth limit of 7 levels. At that point we just stop serializing fields that have types of custom classes/structs and lists and arrays.
Since so many of our subsystems build ontop of the serialization system, this unexpectedly big serializationstream for the Test monobehaviour will cause all these subsystems to perform more slowly than necissery. When we investigate performance problems in customer projects, almost always do we find this problem. We added a warning for this situation in Unity 4.5.
Embarassing. And how many times have I read the docs? Thanks!
Answer by Brainversation01 · Jun 04, 2015 at 08:11 AM
For anyone looking for a workaround.
public class NullTest : MonoBehaviour{
private Bar _foo = null;
public Bar foo{
get{
return _foo;
}
set{
_foo = value;
}
}
function Update(){
print(foo);
}
public class Bar{
int parameter;
}
}
Your answer
Follow this Question
Related Questions
Confirming item pickup in inventory 0 Answers
Null reference exception 1 Answer
How do I fix this null problem? 1 Answer
List<> and Crafting null reference. 1 Answer
Problem with a Bool 1 Answer