Search Unity

Serializable Class Automatically Constructed OnAwake?

Discussion in 'Scripting' started by joeyxiong1994, Aug 10, 2019.

  1. joeyxiong1994

    joeyxiong1994

    Joined:
    Apr 18, 2017
    Posts:
    20
    Hi I defined a class like below Screen Shot 2019-08-10 at 09.50.39.png

    Initially, I didn't give it [Serializable]

    And I used it in here:
    Screen Shot 2019-08-10 at 09.51.10.png

    So if without Serializable, when game starts, I need line 26 to construct this object first, and then I can execute line 27. Otherwise, I would get NullObjectFoundException. However, after I give [Serializable], I don't need line 26. It can pass. And from inspector, I can see this dmg attribute:
    Screen Shot 2019-08-10 at 09.50.12.png

    I don't know why after giving [Serializable], I don't need to construct it anymore before using it. Anyone can explain to me? Thanks
     
  2. DonLoquacious

    DonLoquacious

    Joined:
    Feb 24, 2013
    Posts:
    1,667
    There are two factors- making it serializable, and holding the reference in a UnityEngine.Object-derived class (MonoBehaviour/Component/ScriptableObject). The reason is that Unity automatically creates initial copies of serializable object types for use in the inspector, so that you can enter values and have it initialized the way that you want, as your last screenshot shows. If it's not serialized, it's ignored by Unity, you can't edit it into the inspector and no initial copy is created for you, meaning you have to create it yourself.
     
    joeyxiong1994 likes this.