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.

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.