Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question about Unity serialization and auto-implemented properties

Discussion in 'General Discussion' started by NoradZero, Jan 22, 2015.

?

Which form do you favour the most for exposing values to inspector ?

  1. First form

    1 vote(s)
    50.0%
  2. Second form

    1 vote(s)
    50.0%
  3. Mix of both

    0 vote(s)
    0.0%
  1. NoradZero

    NoradZero

    Joined:
    Apr 24, 2014
    Posts:
    95
    Hello,

    I was just curious about how you guys are exposing the values of your types derived by MonoBehavior.

    Form 1. Always use fields.

    Code (csharp):
    1. public float SomeValue;
    2.  
    3. [SerializeField]
    4. private float _someValue;
    Form 2. Use auto-implemented properties. (in case you need encapsulation logic)

    Code (csharp):
    1. public float SomeValue
    2. {
    3.   get { return _someValue; }
    4.   protected set { _someValue = value; }
    5. }
    6.  
    7. [SerializeField]
    8. private float _someValue;
    Are you guys always use the first form for exposing your values on the inspector ?
    Or would you favor this in case you need to set a protection level on a backing field or encapsulation logic the second form ?
    Or would you use a mix of the two ?


    Thanks!
     
  2. Deleted User

    Deleted User

    Guest

    mostly the second one and set the poperty in OnValidate() to ensure validation when the value is changed in the inspector.
    BTW your example isnt auto implemented ;-)
     
  3. NoradZero

    NoradZero

    Joined:
    Apr 24, 2014
    Posts:
    95
    True.

    Auto-implemented is basically ...
    Code (csharp):
    1. public string SomeValue { get; set; }
    But to me the second example was equivalent in the functionality so i somewhat included it in the boat :)