Search Unity

Question How do I set a serialized class variable to null in inspector of a monobehavior class?

Discussion in 'Scripting' started by Upp000, May 31, 2023.

  1. Upp000

    Upp000

    Joined:
    Mar 4, 2021
    Posts:
    96
    If I have a serialized class variable in a monobehavior class, it will automatically be serialized and not be null if the monobehavior class is attached to a gameobject.
    But sometimes I don't really that data, I want it to stay null so that I wouldn't have to spawn unneeded data when I spawn gameobjects with that monobahavior.
    How do I do that?
    (I know system.nonserialized, no, I want it to be serialized when I need the data)
     
  2. Bunny83

    Bunny83

    Joined:
    Oct 18, 2010
    Posts:
    4,011
    Normal inline serialization does not support null values except for UnityEngine.Object references (or derived types). Custom serializable classes can not be null.

    However you can use the relatively new SerializeReference attribute which does support null, but has some overhead and you are responsible for actually creating the instances. You usually need a custom inspector or property drawer in conjunction.

    See the manual for more details on serialization.
     
    orionsyndrome likes this.
  3. Upp000

    Upp000

    Joined:
    Mar 4, 2021
    Posts:
    96
    thanks, I guess I will ignore it instead, too much works, too little return. Or maybe I just use scriptable object
     
  4. orionsyndrome

    orionsyndrome

    Joined:
    May 4, 2014
    Posts:
    3,116
    Only SerializeReference can help you. With standard stuff, no 'nothing' on deserialization is allowed, an object will pop into existence no matter what.