Created
October 16, 2018 15:26
-
-
Save edwardrowe/d4c21e014e39fe15f8ecbb440eedffad to your computer and use it in GitHub Desktop.
UnityTip-Serializing Preferences (10/16/18)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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