Skip to content

Instantly share code, notes, and snippets.

@ashblue
Created July 31, 2017 15:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ashblue/dbdd176db158af834cfe5ecba8d1fdfb to your computer and use it in GitHub Desktop.
Save ashblue/dbdd176db158af834cfe5ecba8d1fdfb to your computer and use it in GitHub Desktop.
Save and restore objects to the editor prefs
using UnityEditor;
using UnityEngine;
namespace Adnc.EditorHelpers {
public static class EditorPrefsObjectHelper {
/// <summary>
/// Save the object to the editor prefs. Only persists for the current editor session
/// </summary>
/// <param name="key"></param>
/// <param name="obj"></param>
public static void SaveObject (string key, Object obj) {
var val = obj == null ? -1 : obj.GetInstanceID();
EditorPrefs.SetInt(key, val);
}
/// <summary>
/// Restore the object from editor prefs
/// </summary>
/// <param name="key"></param>
/// <param name="nullValue"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static T RestoreObject<T> (string key, T nullValue = null) where T : Object {
var id = EditorPrefs.GetInt(key, -1);
var result = EditorUtility.InstanceIDToObject(id);
if (result == null) {
return nullValue;
}
return result as T;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment