Search Unity

Int Array created as empty instead of null

Discussion in 'Scripting' started by ScottAdams, Aug 4, 2021.

  1. ScottAdams

    ScottAdams

    Joined:
    Nov 23, 2016
    Posts:
    72
    In a monobehaviour class I had


    Code (CSharp):
    1.     /// <summary>
    2.     /// All current assigned bounties
    3.     /// </summary>
    4.     [HideInInspector]
    5.     public int[] Bounties = null;
    6.  
    Using debugger I looked at Bounties in the Awake() function and it was set to int[0] which is an empty array but not null! I could set it to null there and it was fine after that.

    What is going on?
     
  2. Lekret

    Lekret

    Joined:
    Sep 10, 2020
    Posts:
    358
    All classes except UnityEngine.Object are serialized as structs, i.e. class won't be null, it will have all fields as default. Array will be an empty array. You can use property instead of [HideInInspector] field, it isn't serialized and will be null.
     
  3. Bunny83

    Bunny83

    Joined:
    Oct 18, 2010
    Posts:
    3,999
    Note that HideInInspector will just hide the field but still serialize it. If you don't that that field to be serialized you have to use "System.NonSerialized". Over here I once posted a table to give an overview of the available attributes and how they are combined.
     
    Lekret, Vryken and ScottAdams like this.