Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

Discussion Best way to implement readonly fields for ScriptableObject data

Discussion in 'Open Projects' started by jhocking-qualcomm, Jun 20, 2022.

  1. jhocking-qualcomm

    jhocking-qualcomm

    Joined:
    Jul 16, 2021
    Posts:
    3
    I don't know if this is really an improvement or something worth changing, but I noticed something subtle while snooping around the ScriptableObjects for storing data. For example, refer to around line 97 here:
    https://github.com/UnityTechnologie...ct/Assets/Scripts/Dialogues/DialogueDataSO.cs

    I used to use that same approach (also described in this thread) to make values that can be set in the editor but read-only to other classes:
    https://www.reddit.com/r/Unity3D/comments/2iymrg/read_only_parameter_with_serializefield_and/

    However I saw an even shorter approach in this thread:
    https://forum.unity.com/threads/serialize-readonly-field.426525/

    In there, it's pointed out that you can accomplish it with this syntax:
    Code (CSharp):
    1. [field:SerializeField] public int Id { get; private set; }
    Ultimately that amounts to basically the same thing (using the automatic backing field, instead of explicitly declaring one) so it's kinda just interesting trivia at this point.
     
    eduardoromeueberts likes this.