Search Unity

how to save a field in custom Editor only?

Discussion in 'Scripting' started by craig4android, Jun 11, 2019.

  1. craig4android

    craig4android

    Joined:
    May 8, 2019
    Posts:
    124
    Code (CSharp):
    1. class mono : MonoBehaviour
    2. {
    3.  
    4.     public int other;
    5.  
    6. }
    7.  
    8. [CustomEditor(typeof(mono), true)]
    9. class monoEditor : Editor
    10. {
    11.  
    12.     int someint;  // i want this int to be different for every instance of mono and to be saved when I restart Unity
    13.  
    14.     public override void OnInspectorGUI()
    15.     {
    16.         base.OnInspectorGUI();
    17.         someint++;
    18.         if (someint % 3 == 0)
    19.         {
    20.             ((mono)target).other = someint;
    21.         }
    22.     }
    23.  
    24. }
     
  2. HarvesteR

    HarvesteR

    Joined:
    May 22, 2009
    Posts:
    531
    EditorPrefs is your friend here.
    Code (CSharp):
    1.  
    2. public static int myValue
    3.    {
    4.        get { return EditorPrefs.GetInt("MyCustomEditor.MyValue", defaultValue); }
    5.        set { EditorPrefs.SetInt("MyCustomEditor.MyValue", value); }
    6.    }
    7.  
    Note that there probably is a performance cost to accessing EditorPrefs very frequently, but for editor code, you usually get to get away with such crimes. :)

    Cheers
     
  3. print_helloworld

    print_helloworld

    Joined:
    Nov 14, 2016
    Posts:
    231
    You'll need to use the instance id of the `target` as the pref key to get and set the preference.
    Code (CSharp):
    1. private void OnEnable()
    2. {
    3.     key = target.GetInstanceID();
    4.     someint = EditorPrefs(key + ".someint", 0);
    5. }
     
  4. craig4android

    craig4android

    Joined:
    May 8, 2019
    Posts:
    124
  5. HarvesteR

    HarvesteR

    Joined:
    May 22, 2009
    Posts:
    531

    The instance ID isn't guaranteed to match across multiple sessions. That might work to store settings for multiple instances over a session, but you're going to fill up EditorPrefs with values that are never re-used. It's a leak situation.

    Ideally, you'd assign each instance a unique id that is guaranteed to always be the same for that instance on every session. If they spawn by code, it could be a hash of the object name where the name gets an incremental value, like 'myObject_1', ',myObject_2' and so on.

    Cheers
     
  6. print_helloworld

    print_helloworld

    Joined:
    Nov 14, 2016
    Posts:
    231
    Yeah, having a lot of keys will become problematic for the registry due to leaks. So you could instead serialiaze a sequence of values into a single pref, like an array would, and if you manage to get a sequential ID assignment to every instance then you could possibly map it directly to the pref.