Skip to content

Instantly share code, notes, and snippets.

@edwardrowe
Created October 16, 2018 15:26
Show Gist options
  • Save edwardrowe/d4c21e014e39fe15f8ecbb440eedffad to your computer and use it in GitHub Desktop.
Save edwardrowe/d4c21e014e39fe15f8ecbb440eedffad to your computer and use it in GitHub Desktop.
UnityTip-Serializing Preferences (10/16/18)
[System.Serializable]
private struct MyEditorToolPreferences
{
// Private fields with the SerializeField attribute will be saved
[SerializeField]
private int savedInt;
// Public fields are also serializable (though I prefer private with the attribute)
public bool SavedBool;
// Property just to show how to expose access to the private field
public int SavedInt
{
get
{
return this.savedInt;
}
set
{
this.savedInt = value;
}
}
}
// Sample of a tool that uses the preferences
public class MyEditorToolWindow : EditorWindow
{
private readonly string PrefsKey = "RedBlueGames.MyEditorToolPrefs";
private MyEditorToolPreferences CurrentPreferences {get; set;}
private void OnEnable()
{
this.LoadSavedPreferences();
}
private void OnDisble()
{
this.SavePreferences();
}
private void SavePreferences()
{
EditorPrefs.SetString(PrefsKey, JsonUtility.ToJson(this.CurrentPreferences));
}
private void LoadSavedPreferences()
{
var serializedPrefs = EditorPrefs.GetString(PrefsKey);
if (!string.IsNullOrEmpty(serializedPrefs))
{
this.CurrentPreferences = JsonUtility.FromJson<MyEditorToolPreferences>(serializedPrefs);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment