Search Unity

Class not using default values in inspector

Discussion in 'Scripting' started by Desprez, Oct 13, 2015.

  1. Desprez

    Desprez

    Joined:
    Aug 31, 2012
    Posts:
    305
    Maybe I'm overlooking something silly here:

    Code (CSharp):
    1. public WeaponData[] weapons;
    2.  
    3. [System.Serializable]
    4. public class WeaponData {
    5.     public GameObject weapon;
    6.     public bool active = true;
    7.     [HideInInspector] public MF_BasicWeapon script;
    8. }
    In the inspector, 'weapons' is an array of size 0.
    When I type in a new number, new array items are created, but the value of 'active' is always false, and not true like I've set in the class.
     
  2. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,532
    resizing arrays in the unity inspector actually doesn't create new instances of the class and serialize that. Instead it duplicates the last entry in the existing serialized representation of the array. If that serialized representation is empty, it creates them with the default values of the types for those fields.

    It's just the weird way unity serializes arrays.
     
    RunninglVlan and Desprez like this.
  3. martinmr

    martinmr

    Joined:
    Mar 25, 2015
    Posts:
    325
    public List<WeaponData> weapons = new List<WeaponData>();

    don't know if resizing arrays in inspector works so well as @lordofduct said.
     
  4. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,532
    Lists are treated nearly the same exact way during serialization.
     
  5. martinmr

    martinmr

    Joined:
    Mar 25, 2015
    Posts:
    325