BS 0.1 基础构建完成 / 0.2 Visual 同为Unity UI控件部分

This commit is contained in:
2025-07-21 15:49:39 +08:00
parent e400c616f4
commit f6750189d0
1768 changed files with 184236 additions and 0 deletions

114
Convention/[ES3]/ES3.cs Normal file
View File

@@ -0,0 +1,114 @@
using UnityEngine;
namespace Convention
{
public interface IES3 { }
public static class ES3Plugin
{
#region Base Save
public static void Save<T>(string path, T data)
{
Save("easy", data, path);
}
public static void Save(string path, object data)
{
Save("easy", data, path);
}
public static void Save<T>(string key, T data, string path)
{
ES3.Save(key, data, path);
}
public static void Save(string key, object data, string path)
{
ES3.Save(key, data, path);
}
#endregion
#region Base Load
public static T Load<T>(string path)
{
return Load<T>("easy", path);
}
public static object Load(string path)
{
return ES3.Load("easy", path);
}
public static T Load<T>(string key, string path)
{
return ES3.Load<T>(key, path);
}
public static object Load(string key, string path)
{
return ES3.Load(key, path);
}
#endregion
public static void Save(this IES3 self, string path) => Save<object>(path, self);
public static void Save(this IES3 self, string key, string path) => Save<object>(key, self, path);
public static void QuickSave(this object self, string path) => Save(path, self);
public static void QuickSave(this object self, string key, string path) => Save(key, self, path);
#region Other Load
public static byte[] LoadRawBytes(string filePath) => ES3.LoadRawBytes(filePath);
public static string LoadRawString(string filePath) => ES3.LoadRawString(filePath);
public static Texture2D LoadImage(string imagePath) => ES3.LoadImage(imagePath);
public static Texture2D LoadImage(byte[] bytes) => ES3.LoadImage(bytes);
public static AudioClip LoadAudio(string audioFilePath
#if UNITY_2018_3_OR_NEWER
, AudioType audioType
) => ES3.LoadAudio(audioFilePath, audioType);
#else
)=>ES3.LoadAudio(audioFilePath);
#endif
#endregion
public static Texture2D ConvertTexture2D(byte[] bytes) => ES3.LoadImage(bytes);
#region Serialize/Deserialize
public static byte[] Serialize<T>(T value) => ES3.Serialize(value);
public static T Deserialize<T>(byte[] bytes) => ES3.Deserialize<T>(bytes);
public static void DeserializeInto<T>(byte[] bytes, T obj) where T : class => ES3.DeserializeInto(bytes, obj);
#endregion
public static byte[] Serialize(this IES3 self) => Serialize<object>(self);
public static T DeserializeFrom<T>(this T self, byte[] bytes) where T : class, IES3
{
DeserializeInto(bytes, self);
return self;
}
#region Encrypt/Decrypt
public static byte[] EncryptBytes(byte[] bytes, string password = null) => ES3.EncryptBytes(bytes, password);
public static byte[] DecryptBytes(byte[] bytes, string password = null) => ES3.DecryptBytes(bytes, password);
public static string EncryptString(string str, string password = null) => ES3.EncryptString(str, password);
public static string DecryptString(string str, string password = null) => ES3.DecryptString(str, password);
public static byte[] CompressBytes(byte[] bytes) => ES3.CompressBytes(bytes);
public static byte[] DecompressBytes(byte[] bytes) => ES3.DecompressBytes(bytes);
public static string CompressString(string str) => ES3.CompressString(str);
public static string DecompressString(string str) => ES3.DecompressString(str);
#endregion
public static void InitExtensionEnv()
{
ES3.Init();
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 8a6a47ee74ef44a4ca8de62277b67d1a
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 38b10e4b0241a8f42a92f19f7b8f9cab
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 06883e65282f91b4e94a4101f6141c16
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,207 @@
3.5.6
- ES3GameObject Component is now automatically moved to end of Components List to ensure that it's loaded after the Components it references.
- Resolved merge issue where cached data was being stored with it's generic type rather than actual type.
- Resolved issue where private members of inherited types wouldn't be saved in specific circumstances.
3.5.5
- References are now gathered when saving a scene and when changes are made in a scene, not when entering playmode.
- Added option to refresh reference managers in all scenes (Tools > Easy Save 3 > Refresh References for All Scenes).
- Added option to exclude references from being added to the manager (right-click > Easy Save 3 > Exclude Reference(s) from Manager).
- Added GetColumnLength and GetRowLength methods to ES3Spreadsheet.
- Resolved issue where enums would cause a FormatException when they were fields of a class with an ES3Type.
- Worked around Unity bug where initialisation events are sometimes not called when importing Easy Save.
- Worked around Unity bug where GetDirectoryName fails to work with a path to a file.
- Auto Saves are now processed in order of their position in the hierarchy.
- Resolved issue where members would be serialized twice when it was marked as ES3Serializable in both concrete and base classes.
- Worked around Unity bug where Unity would throw an error when trying to set a scripting define symbol for Stadia.
- Accounted for change in 2022.3 LTS where Unity have fixed a typo in their Editor API ("ToolbarSeachTextField")
3.5.4
- You can now enable Assembly Definition Files for Easy Save by going to Tools > Easy Save 3 > Enable Assembly Definition Files.
- Accounted for edge case where ES3File would be merged rather than overwritten, preventing keys from being deleted from the stored file.
- Resolved issue where reference collection can cause an InvalidOperationException (Collection was modified).
- Worked around bug with Unity Runner Template which prevented Easy Save types from loading.
- overrideSprite is no longer saved when saving UI.Image as Unity now returns the Sprite rather than null when this is unassigned.
- Resolved issue where Auto Save's events sometimes did not update when changing the active scene in the Editor.
- Resolved issue where saving a non-prefab instance GameObject with multiple Components would only save one of those Components.
3.5.3
- Attempting to save a Material with a RenderTexture will now throw a warning indicating that the RenderTexture won't be saved.
- Added filtering by tag in the Auto Save window by prefixing 'tag:' to the search query.
3.5.2
- Resolved issue where RectTransform was loaded incorrectly as parent is deserialized before anchoredPosition.
- Removed warning regarding Transform parents being set using the accessor rather than the SetParent method.
- ES3.CopyFile now automatically creates the target directory if it doesn't exist.
- Added an option to encrypt/compress raw cached data if the setting is defined for the cached file (postprocessRawCachedData).
- 'Add References to Manager' now permanently adds prefabs to the manager if 'Auto Add Prefabs to Manager' is enabled.
- Assembly names are now in alphabetical order so changes in order aren't registered as a change in version control.
- Using 'Add References to Manager' on a folder now adds all supported assets in that folder to the reference manager.
3.5.1
- Reverted changes to LoadRaw methods when using Cache as it caused regression issues.
3.5.0
- Added support for NativeArray.
- Managed case where ES3.EncryptBytes/DecryptBytes encountered an encoding issue.
- Worked around Unity bug where invalid assembly list would cause issues when exceptions are disabled.
- Worked around bug at Unity's end where unloaded scenes are returned by their methods.
- Resolved issue where scripting define symbols were overwritten on older versions of Unity.
- Worked around bug where inertia tensor value is rejected even when set as it's default upon loading.
- Most Material properties can now be saved, including custom properties.
- When saving a parent GameObject, children automatically have their parent set to the parent GameObject rather than loading this value by reference.
- Support added for Tuples.
- Added overload for AppendRaw which accepts a string and a filename.
- Worked around Unity bug where EventType.Layout isn't called when moving tabs for first time, causing Types pane recent types to be uninitialised.
- Worked around Unity bug which infrequently prevented Auto Save changes from persisting.
- Added ES3.Compress and ES3.Decompress methods.
- Performing 'Add Reference(s) to Manager' for a Texture2D will also add it's Sprite if one is present.
- Classes without parameterless constructors can now be serialised (note that their constructor will not be called).
- Resolved issue where an unloaded scene warning was thrown when scene is open but manually marked as unloaded in the Editor.
3.4.2
- Resolved issue where Unity Visual Scripting defines were not present on some versions of Unity.
3.4.1
- Added support for Particle System Bursts
- Resolved issue where Auto Save would sometimes save all Components regardless of settings.
- Resolved issue where Auto Save icon would not highlight when fields are selected.
- Structs with private properties or fields can now be serialized.
- Loading a blank string from a spreadsheet now returns a blank string rather than null.
- The reference manager will only collect references up to 3 levels deep to improve performance.
- System.Random support has been dropped due to Unity's implementation changing, making it non-serializable.
- ES3Ref is no longer stored twice for ScriptableObjects.
- Added support for Numerics.BigInteger.
- Internal fields of the ES3AutoSave Component are no longer displayed in the Editor.
- If a reference ID for a Component exists, it now ignores the GameObject ID so that a new GO instance is not created.
- Added a Get Streaming Assets Path action for Playmaker.
- Added non-generic versions of the ES3Spreadsheet methods to work around issue with Bolt.
- Worked around issue with Bolt where it would crash if you have two methods with the same parameters but one is generic.
- Resolved issue where Components marked as destroyed but not yet destroyed would cause unexpected behaviour.
- Auto Save will now work for additive scenes.
- Resolved issue where reference manager wasn't automatically updated when scene was open additively prior to runtime.
- Support added for Unity Visual Scripting.
3.4.0
- Caching now works seamlessly between Cloud and Auto Save.
- Added Save Multiple and Load Multiple actions to enable saving multiple specific variables at once.
- Added extra overloads to the ES3.LoadString method.
- Guids are now natively supported.
- Transform now stores the sibling index.
- Getting a timestamp for a file in cache which doesn't exist now returns a zero timestamp.
- Resolved issues where enums would sometiimes not serialize correctly when creating an ES3Type script for a class.
- Resolved issue where DownloadTimestamp PlayMaker action would download the wrong data.
- Resolved issue where reflection does not recognise a collection of a nested type as a nested type.
- Resolved issue where ES3Cloud was merged with the debug branch.
- Resolved issue where Sprites with atlased Textures would save an incorrect Rect.
- Resolved issue where ES3Spreadsheet was serializing primitives as objects when using PlayMaker actions.
3.3.2f7
- Type data is now stored when using ES3.Serialize<object>.
- Worked around issue where Unity would return an incorrect number of assemblies.
3.3.2f6
- ES3Spreadsheet now correctly serializes object types into a CSV file.
- Resolved issue where an object[] containing primitive types could not be loaded in some situations.
- Worked around issue where PlayMaker wouldn't initialize variable before it's value was reset.
- Created a workaround for some situations where Unity creates new instances of ScriptableObjects in Assets at runtime.
- Resolved issue where Base-64 encoding option would not work with newline option in PlayMaker SaveRaw action.
3.3.2f5
- Resolved issue where scripts were not overwritten by Asset Store importer, causing Easy Save to be unstable.
3.3.2f4
- Resolved issue where Save action for PlayMaker could return NullReferenceException due to using the wrong ES3.Save override.
- Worked around IL2CPP bug where reflection would not find particular ES3Types on iOS
- Resolved issue where trying to store an empty/unassigned PlayMaker object would throw a NulReferenceException.
- Keys of a type which no longer exists in the project are now automatically removed
- Abstract types used in an ES3Type will now work as intended
3.3.2f3
- Added GameObject variables to Auto Save
- Resolved issue where Sprites would be loaded with the incorrect pivot.
- Resolved issue where Stacks were loaded in reverse.
- Added a 'quality' field to the ES3.SaveImage method to allow the quality to be specified when saving JPEGs.
3.3.2f2
- Added method which allows raw bytes to be uploaded via ES3Cloud.
- Worked around issue where File IO was called on platforms which don't support it
- Accounted for situations where Component should evaluate to null but doesn't
- Updated PlayMaker actions to work around issue where global variables sometimes go missing
- Objects with the NotEditable hideFlags can now be stored by reference
- Worked around Unity bug where it fails to deserialize data when Prefab mode is open
- Resolved issue where global 'Save GameObject Children' settings can take precedence over Auto Save settings
- 'Enable Easy Save for Prefab' context menu item now works when multiple objects are selected.
3.3.2f1
- Resolved issue where Components on prefabs would sometimes not be added to the reference manager.
- Resolved issue where reference ID was read unnecesserily, causing format exception.
- Resolved issue where child prefabs would not be recognised by manager.
3.3.1p12
- Resolved case where certain references would not be added to manager.
3.3.1f11
- Fixed issue where using ES3.CacheFile with an encrypted file could fail.
- Fixed issue where Directory.GetFiles cannot process a full path on certain configurations.
- Accounted for case where HideFlags are changed during build process.
- Added a timeout parameter to the ES3Cloud constructor.
- ES3.Serialize and ES3.Deserialize now work with encryption and compression
3.3.1f10
- Full support for projects which use multiple scenes at once.
- Added ES3.Encrypt and ES3.Decrypt methods.
- Supported saving the active state and FsmVariables of PlayMaker FSMs.
- Added edge case for SkinnedMeshRenderers which use LODs to ensure that all meshes and Materials are added to the reference manager.
- Ensured that Auto Update References setting is ackowledged when first adding manager to scene.
- Moved menu items into Tools/Easy Save 3 menu.
- Using LoadInto will now assign the loaded reference ID to the object you're loading into.
3.3.1f9
- It's not possible to add an ES3ReferenceMgr to your scene directly, ensuring that initialisation code is performed.
- Compressed files can now be cached.
- Ability to only add prefabs directly referenced by your scene to the manager.
3.3.1f8
- Caching is now enabled by default for Auto Save, significantly improving performance.
- Added ES3.LoadString method so you do not need to provide all parameters to use the defaultValue overload.
- Resolved case where SaveAll would not correctly save some types of array.
- Resolved case where global references would not be acknowledged.
3.3.1f7
- Serialization depth limit has been raised to account for projects with deep hierearchies
- Fixed issue where Easy Save 3 Manager could not be found for scenes which had not been saved.
- Resolved issue where Add Reference(s) to Manager would not dirty scene when Auto Update References was disabled.
- Improved Editor performance by accounting for situations where post-processing events would be called multiple times.
3.3.1f6
- Internal fields of the UnityEngine.Object class are hidden in the Types pane as they are not serialisable.
- Accounted for edge case where unassigned script is returned by GameObject.GetComponents().
- ES3Settings constructor now accepts any settings enum (e.g. ES3.Location).
- No longer throws warning when multiple scenes are open.
3.3.1f5
- Updated PlayMaker actions.
- Provided workaround for issue where IL2CPP stripper removes methods which are marked to not be stripped.
- Performance updates.
3.3.1f4
- Improved performance when gathering references for reference manager.
3.3.1f3
- Added Cache as a storage location, providing a much simpler way of caching data.
- References can now be added by right-clicking the object and going to Easy Save 3 > Add Reference to Manager.
- Floats and doubles are now stored with full precision.
- Assorted bug fixes.
3.3.1f2
- Added compression, reducing file size by 85% on average when enabled
- JSON is now pretty printed (formatted) by default
- Added attributes to control serialisation
- Private fields in inherited classes are now stored
- Added search capabilities to the Auto Save window
- The way in which GameObjects is saved is now more flexible
- The reference manager is now updated whenever playmode is entered
- Null values in the global manager are now automatically removed
- Fixed issue where default settings were not applied properly
- Fixed issue where ES3Types would be stored in Easy Save root rather than in Assets/Easy Save 3/

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: c4bcd2b2d304b82499fb23250a1bf736
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,16 @@
{
"name": "EasySave3",
"rootNamespace": "",
"references": [
"Unity.VisualScripting.Core"
],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": false
}

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 067fa8909b51a584b8bdcf66fda1d2e0
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: a1b367e4df658ad4384a03cfb4773957
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,86 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using ES3Internal;
using System.Linq;
namespace ES3Editor
{
public class AddES3Prefab : Editor
{
[MenuItem("GameObject/Easy Save 3/Enable Easy Save for Prefab(s)", false, 1001)]
[MenuItem("Assets/Easy Save 3/Enable Easy Save for Prefab(s)", false, 1001)]
public static void Enable()
{
if (Selection.gameObjects == null || Selection.gameObjects.Length == 0)
return;
foreach (var obj in Selection.gameObjects)
{
// Don't add the Component to a GameObject which already has it.
if (obj == null || (obj.GetComponent<ES3Prefab>() != null))
continue;
var go = obj;
#if UNITY_2018_3_OR_NEWER
if (PrefabUtility.GetPrefabInstanceStatus(go) != PrefabInstanceStatus.NotAPrefab)
{
go = (GameObject)PrefabUtility.GetCorrespondingObjectFromSource(go);
if (go == null)
continue;
}
#else
if(PrefabUtility.GetPrefabType(go) != PrefabType.Prefab)
{
go = (GameObject)PrefabUtility.GetPrefabParent(go);
if(go == null)
continue;
}
#endif
var es3Prefab = Undo.AddComponent<ES3Prefab>(go);
es3Prefab.GeneratePrefabReferences();
if (ES3ReferenceMgr.Current != null)
{
ES3ReferenceMgr.Current.AddPrefab(es3Prefab);
EditorUtility.SetDirty(ES3ReferenceMgr.Current);
}
}
}
[MenuItem("GameObject/Easy Save 3/Enable Easy Save for Prefab(s)", true, 1001)]
[MenuItem("Assets/Easy Save 3/Enable Easy Save for Prefab(s)", true, 1001)]
public static bool Validate()
{
return Selection.gameObjects != null && Selection.gameObjects.Length > 0;
}
}
public class RemoveES3Prefab : Editor
{
[MenuItem("GameObject/Easy Save 3/Disable Easy Save for Prefab(s)", false, 1001)]
[MenuItem("Assets/Easy Save 3/Disable Easy Save for Prefab(s)", false, 1001)]
public static void Enable()
{
if (Selection.gameObjects == null || Selection.gameObjects.Length == 0)
return;
foreach (var obj in Selection.gameObjects)
{
var es3prefab = obj.GetComponent<ES3Prefab>();
if (es3prefab != null)
Undo.DestroyObjectImmediate(es3prefab);
}
}
[MenuItem("GameObject/Easy Save 3/Disable Easy Save for Prefab(s)", true, 1001)]
[MenuItem("Assets/Easy Save 3/Disable Easy Save for Prefab(s)", true, 1001)]
public static bool Validate()
{
return Selection.gameObjects != null && Selection.gameObjects.Length > 0;
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 70c798e5a4b5fca4a9aaefe920553119
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,365 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using ES3Internal;
using UnityEngine.SceneManagement;
using UnityEditor.SceneManagement;
namespace ES3Editor
{
[System.Serializable]
public class AutoSaveWindow : SubWindow
{
public bool showAdvancedSettings = false;
public ES3AutoSaveMgr mgr = null;
private HierarchyItem[] hierarchy = null;
public HierarchyItem selected = null;
private Vector2 hierarchyScrollPosition = Vector2.zero;
private bool sceneOpen = true;
private string searchTerm = "";
public AutoSaveWindow(EditorWindow window) : base("Auto Save", window)
{
EditorSceneManager.activeSceneChangedInEditMode += ChangedActiveScene;
}
private void ChangedActiveScene(Scene current, Scene next)
{
mgr = null;
Init();
}
public override void OnGUI()
{
Init();
if(mgr == null)
{
EditorGUILayout.Space();
if (GUILayout.Button("Enable Auto Save for this scene"))
mgr = ES3Postprocessor.AddManagerToScene().GetComponent<ES3AutoSaveMgr>();
else
return;
}
var style = EditorStyle.Get;
using (var changeCheck = new EditorGUI.ChangeCheckScope())
{
using (var vertical = new EditorGUILayout.VerticalScope(style.areaPadded))
{
//GUILayout.Label("Settings for current scene", style.heading);
mgr.saveEvent = (ES3AutoSaveMgr.SaveEvent)EditorGUILayout.EnumPopup("Save Event", mgr.saveEvent);
mgr.loadEvent = (ES3AutoSaveMgr.LoadEvent)EditorGUILayout.EnumPopup("Load Event", mgr.loadEvent);
EditorGUILayout.Space();
showAdvancedSettings = EditorGUILayout.Foldout(showAdvancedSettings, "Show Advanced Settings");
if (showAdvancedSettings)
{
EditorGUI.indentLevel++;
mgr.key = EditorGUILayout.TextField("Key", mgr.key);
ES3SettingsEditor.Draw(mgr.settings);
EditorGUI.indentLevel--;
}
}
// Display the menu.
using (var horizontal = new EditorGUILayout.HorizontalScope())
{
if (GUILayout.Button("Scene", sceneOpen ? style.menuButtonSelected : style.menuButton))
{
sceneOpen = true;
OnFocus();
}
if (GUILayout.Button("Prefabs", sceneOpen ? style.menuButton : style.menuButtonSelected))
{
sceneOpen = false;
OnFocus();
}
}
//EditorGUILayout.HelpBox("Select the Components you want to be saved.\nTo maximise performance, only select the Components with variables which need persisting.", MessageType.None, true);
if (hierarchy == null || hierarchy.Length == 0)
{
EditorGUILayout.LabelField("Right-click a prefab and select 'Easy Save 3 > Enable Easy Save for Scene' to enable Auto Save for it.\n\nYour scene will also need to reference this prefab for it to be recognised.", style.area);
return;
}
using (var scrollView = new EditorGUILayout.ScrollViewScope(hierarchyScrollPosition, style.areaPadded))
{
hierarchyScrollPosition = scrollView.scrollPosition;
using (new EditorGUILayout.HorizontalScope(GUILayout.Width(200)))
{
#if UNITY_2022_3_OR_NEWER
searchTerm = GUILayout.TextField(searchTerm, GUI.skin.FindStyle("ToolbarSearchTextField"));
if (GUILayout.Button("", GUI.skin.FindStyle("ToolbarSearchCancelButton")))
#else
searchTerm = GUILayout.TextField(searchTerm, GUI.skin.FindStyle("ToolbarSeachTextField"));
if (GUILayout.Button("", GUI.skin.FindStyle("ToolbarSeachCancelButton")))
#endif
{
// Remove focus if cleared
searchTerm = "";
GUI.FocusControl(null);
}
}
EditorGUILayout.Space();
EditorGUILayout.Space();
foreach (var go in hierarchy)
if (go != null)
go.DrawHierarchy(searchTerm.ToLowerInvariant());
}
if (changeCheck.changed)
EditorUtility.SetDirty(mgr);
}
}
public void Init()
{
if (mgr == null)
foreach (var thisMgr in Resources.FindObjectsOfTypeAll<ES3AutoSaveMgr>())
if (thisMgr != null && thisMgr.gameObject.scene == SceneManager.GetActiveScene())
mgr = thisMgr;
if (hierarchy == null)
OnFocus();
}
public override void OnFocus()
{
GameObject[] parentObjects;
if (sceneOpen)
parentObjects = UnityEngine.SceneManagement.SceneManager.GetActiveScene().GetRootGameObjects();
else // Prefabs
{
var prefabs = ES3ReferenceMgr.Current.prefabs;
parentObjects = new GameObject[prefabs.Count];
for (int i = 0; i < prefabs.Count; i++)
if(prefabs[i] != null)
parentObjects[i] = prefabs[i].gameObject;
}
hierarchy = new HierarchyItem[parentObjects.Length];
for (int i = 0; i < parentObjects.Length; i++)
if(parentObjects[i] != null)
hierarchy[i] = new HierarchyItem(parentObjects[i].transform, null, this);
}
public class HierarchyItem
{
private ES3AutoSave autoSave;
private Transform t;
private Component[] components = null;
// Immediate children of this GameObject
private HierarchyItem[] children = new HierarchyItem[0];
private bool showComponents = false;
//private AutoSaveWindow window;
public HierarchyItem(Transform t, HierarchyItem parent, AutoSaveWindow window)
{
this.autoSave = t.GetComponent<ES3AutoSave>();
this.t = t;
this.components = t.GetComponents<Component>();
children = new HierarchyItem[t.childCount];
for (int i = 0; i < t.childCount; i++)
children[i] = new HierarchyItem(t.GetChild(i), this, window);
//this.window = window;
}
public void MergeDown(ES3AutoSave autoSave)
{
if (this.autoSave != autoSave)
{
if (this.autoSave != null)
{
autoSave.componentsToSave.AddRange(autoSave.componentsToSave);
Object.DestroyImmediate(this.autoSave);
}
this.autoSave = autoSave;
}
foreach (var child in children)
MergeDown(autoSave);
}
public void DrawHierarchy(string searchTerm)
{
bool containsSearchTerm = false;
if (t != null)
{
// Filter by tag if it's prefixed by "tag:"
if (searchTerm.StartsWith("tag:") && t.tag.ToLowerInvariant().Contains(searchTerm.Remove(0,4)))
containsSearchTerm = true;
// Else filter by name
else
containsSearchTerm = t.name.ToLowerInvariant().Contains(searchTerm);
if (containsSearchTerm)
{
GUIContent saveIcon;
EditorGUIUtility.SetIconSize(new Vector2(16, 16));
if (HasSelectedComponentsOrFields())
saveIcon = new GUIContent(t.name, EditorStyle.Get.saveIconSelected, "There are Components on this GameObject which will be saved.");
else
saveIcon = new GUIContent(t.name, EditorStyle.Get.saveIconUnselected, "No Components on this GameObject will be saved");
GUIStyle style = GUI.skin.GetStyle("Foldout");
if (Selection.activeTransform == t)
{
style = new GUIStyle(style);
style.fontStyle = FontStyle.Bold;
}
var open = EditorGUILayout.Foldout(showComponents, saveIcon, style);
if (open)
{
// Ping the GameObject if this was previously closed
if (showComponents != open)
EditorGUIUtility.PingObject(t.gameObject);
DrawComponents();
}
showComponents = open;
EditorGUI.indentLevel += 1;
}
}
// Draw children
if (children != null)
foreach (var child in children)
if (child != null)
child.DrawHierarchy(searchTerm);
if (containsSearchTerm)
EditorGUI.indentLevel -= 1;
}
public void DrawComponents()
{
EditorGUI.indentLevel += 3;
using (var scope = new EditorGUILayout.VerticalScope())
{
bool toggle;
toggle = EditorGUILayout.ToggleLeft("active", autoSave != null ? autoSave.saveActive : false);
if ((autoSave = (toggle && autoSave == null) ? t.gameObject.AddComponent<ES3AutoSave>() : autoSave) != null)
ApplyBool("saveActive", toggle);
toggle = EditorGUILayout.ToggleLeft("hideFlags", autoSave != null ? autoSave.saveHideFlags : false);
if ((autoSave = (toggle && autoSave == null) ? t.gameObject.AddComponent<ES3AutoSave>() : autoSave) != null)
ApplyBool("saveHideFlags", toggle);
toggle = EditorGUILayout.ToggleLeft("layer", autoSave != null ? autoSave.saveLayer : false);
if ((autoSave = (toggle && autoSave == null) ? t.gameObject.AddComponent<ES3AutoSave>() : autoSave) != null)
ApplyBool("saveLayer", toggle);
toggle = EditorGUILayout.ToggleLeft("name", autoSave != null ? autoSave.saveName : false);
if ((autoSave = (toggle && autoSave == null) ? t.gameObject.AddComponent<ES3AutoSave>() : autoSave) != null)
ApplyBool("saveName", toggle);
toggle = EditorGUILayout.ToggleLeft("tag", autoSave != null ? autoSave.saveTag : false);
if ((autoSave = (toggle && autoSave == null) ? t.gameObject.AddComponent<ES3AutoSave>() : autoSave) != null)
ApplyBool("saveTag", toggle);
foreach (var component in components)
{
if (component == null)
continue;
using (var horizontalScope = new EditorGUILayout.HorizontalScope())
{
bool saveComponent = false;
if (autoSave != null)
saveComponent = autoSave.componentsToSave.Contains(component);
var newValue = EditorGUILayout.ToggleLeft(EditorGUIUtility.ObjectContent(component, component.GetType()), saveComponent);
// If the checkbox has changed, we want to save or not save a Component
if (newValue != saveComponent)
{
if (autoSave == null)
{
autoSave = Undo.AddComponent<ES3AutoSave>(t.gameObject);
var so = new SerializedObject(autoSave);
so.FindProperty("saveChildren").boolValue = false;
so.ApplyModifiedProperties();
}
// If we've unchecked the box, remove the Component from the array.
if (newValue == false)
{
var so = new SerializedObject(autoSave);
var prop = so.FindProperty("componentsToSave");
var index = autoSave.componentsToSave.IndexOf(component);
prop.DeleteArrayElementAtIndex(index);
so.ApplyModifiedProperties();
}
// Else, add it to the array.
else
{
var so = new SerializedObject(autoSave);
var prop = so.FindProperty("componentsToSave");
prop.arraySize++;
prop.GetArrayElementAtIndex(prop.arraySize - 1).objectReferenceValue = component;
so.ApplyModifiedProperties();
}
}
if (GUILayout.Button(EditorGUIUtility.IconContent("_Popup"), new GUIStyle("Label")))
ES3Window.InitAndShowTypes(component.GetType());
}
}
}
/*if(autoSave != null && isDirty)
{
EditorUtility.SetDirty(autoSave);
if (PrefabUtility.IsPartOfPrefabInstance(autoSave))
PrefabUtility.RecordPrefabInstancePropertyModifications(autoSave.gameObject);
}*/
if (autoSave != null && (autoSave.componentsToSave == null || autoSave.componentsToSave.Count == 0) && !autoSave.saveActive && !autoSave.saveChildren && !autoSave.saveHideFlags && !autoSave.saveLayer && !autoSave.saveName && !autoSave.saveTag)
{
Undo.DestroyObjectImmediate(autoSave);
autoSave = null;
}
EditorGUI.indentLevel -= 3;
}
public void ApplyBool(string propertyName, bool value)
{
var so = new SerializedObject(autoSave);
so.FindProperty(propertyName).boolValue = value;
so.ApplyModifiedProperties();
}
public bool HasSelectedComponentsOrFields()
{
if (autoSave == null)
return false;
foreach (var component in components)
if (component != null && autoSave.componentsToSave.Contains(component))
return true;
if (autoSave.saveActive || autoSave.saveHideFlags || autoSave.saveLayer || autoSave.saveName || autoSave.saveTag)
return true;
return false;
}
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 50b0c2716805479418e990f347f0cd85
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,21 @@
using UnityEditor;
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
namespace ES3Internal
{
[CustomEditor(typeof(ES3AutoSave))]
public class ES3AutoSaveEditor : Editor
{
public override void OnInspectorGUI()
{
if (target == null)
return;
if (GUILayout.Button("Manage Auto Save Settings"))
ES3Editor.ES3Window.InitAndShowAutoSave();
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 44b585b015d480148be175c3c255f5d8
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,20 @@
using UnityEditor;
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
namespace ES3Internal
{
[CustomEditor(typeof(ES3AutoSaveMgr))]
public class ES3AutoSaveMgrEditor : Editor
{
public override void OnInspectorGUI()
{
EditorGUILayout.HelpBox("This manages the saving and loading of GameObjects which have the Auto Save component attached to them.\n\nIf there are no Auto Save components in your scene, this component will do nothing.", MessageType.Info);
if(GUILayout.Button("Settings..."))
ES3Editor.ES3Window.InitAndShowAutoSave();
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: e82bb37c433f3b64f94746b6e8d5a3ba
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,54 @@
using System;
using UnityEngine;
namespace ES3Types
{
[UnityEngine.Scripting.Preserve]
[ES3PropertiesAttribute([propertyNames])]
public class ES3UserType_[es3TypeSuffix] : ES3ObjectType
{
public static ES3Type Instance = null;
public ES3UserType_[es3TypeSuffix]() : base(typeof([fullType])){ Instance = this; priority = 1; }
protected override void WriteObject(object obj, ES3Writer writer)
{
var instance = ([fullType])obj;
[writes]
}
protected override void ReadObject<T>(ES3Reader reader, object obj)
{
var instance = ([fullType])obj;
foreach(string propertyName in reader.Properties)
{
switch(propertyName)
{
[reads]
default:
reader.Skip();
break;
}
}
}
protected override object ReadObject<T>(ES3Reader reader)
{
var instance = new [fullType]();
ReadObject<T>(reader, instance);
return instance;
}
}
public class ES3UserType_[es3TypeSuffix]Array : ES3ArrayType
{
public static ES3Type Instance;
public ES3UserType_[es3TypeSuffix]Array() : base(typeof([fullType][]), ES3UserType_[es3TypeSuffix].Instance)
{
Instance = this;
}
}
}

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: fd26d61d3367c3347869a48ededaf15f
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,47 @@
using System;
using UnityEngine;
namespace ES3Types
{
[UnityEngine.Scripting.Preserve]
[ES3PropertiesAttribute([propertyNames])]
public class ES3UserType_[es3TypeSuffix] : ES3ComponentType
{
public static ES3Type Instance = null;
public ES3UserType_[es3TypeSuffix]() : base(typeof([fullType])){ Instance = this; priority = 1;}
protected override void WriteComponent(object obj, ES3Writer writer)
{
var instance = ([fullType])obj;
[writes]
}
protected override void ReadComponent<T>(ES3Reader reader, object obj)
{
var instance = ([fullType])obj;
foreach(string propertyName in reader.Properties)
{
switch(propertyName)
{
[reads]
default:
reader.Skip();
break;
}
}
}
}
public class ES3UserType_[es3TypeSuffix]Array : ES3ArrayType
{
public static ES3Type Instance;
public ES3UserType_[es3TypeSuffix]Array() : base(typeof([fullType][]), ES3UserType_[es3TypeSuffix].Instance)
{
Instance = this;
}
}
}

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 431e94a281b3fd84fb1381c3d8f6c509
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,84 @@
using System.Collections;
using UnityEngine;
using UnityEditor;
namespace ES3Editor
{
public class EditorStyle
{
private static EditorStyle style = null;
public GUIStyle area;
public GUIStyle areaPadded;
public GUIStyle menuButton;
public GUIStyle menuButtonSelected;
public GUIStyle smallSquareButton;
public GUIStyle heading;
public GUIStyle subheading;
public GUIStyle subheading2;
public GUIStyle boldLabelNoStretch;
public GUIStyle link;
public GUIStyle toggle;
public Texture2D saveIconSelected;
public Texture2D saveIconUnselected;
public static EditorStyle Get { get{ if(style == null) style = new EditorStyle(); return style; } }
public EditorStyle()
{
// An area with padding.
area = new GUIStyle();
area.padding = new RectOffset(10, 10, 10, 10);
area.wordWrap = true;
// An area with more padding.
areaPadded = new GUIStyle();
areaPadded.padding = new RectOffset(20, 20, 20, 20);
areaPadded.wordWrap = true;
// Unselected menu button.
menuButton = new GUIStyle(EditorStyles.toolbarButton);
menuButton.fontStyle = FontStyle.Normal;
menuButton.fontSize = 14;
menuButton.fixedHeight = 24;
// Selected menu button.
menuButtonSelected = new GUIStyle(menuButton);
menuButtonSelected.fontStyle = FontStyle.Bold;
// Main Headings
heading = new GUIStyle(EditorStyles.label);
heading.fontStyle = FontStyle.Bold;
heading.fontSize = 24;
subheading = new GUIStyle(heading);
subheading.fontSize = 18;
subheading2 = new GUIStyle(heading);
subheading2.fontSize = 14;
boldLabelNoStretch = new GUIStyle(EditorStyles.label);
boldLabelNoStretch.stretchWidth = false;
boldLabelNoStretch.fontStyle = FontStyle.Bold;
link = new GUIStyle();
link.fontSize = 16;
if(EditorGUIUtility.isProSkin)
link.normal.textColor = new Color (0.262f, 0.670f, 0.788f);
else
link.normal.textColor = new Color (0.129f, 0.129f, 0.8f);
toggle = new GUIStyle(EditorStyles.toggle);
toggle.stretchWidth = false;
saveIconSelected = AssetDatabase.LoadAssetAtPath<Texture2D>(ES3Settings.PathToEasySaveFolder() + "Editor/es3Logo16x16.png");
saveIconUnselected = AssetDatabase.LoadAssetAtPath<Texture2D>(ES3Settings.PathToEasySaveFolder() + "Editor/es3Logo16x16-bw.png");
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 9da4a270efed7b840911b170cff4b4d5
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,60 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.IO;
using System.Linq;
using ES3Internal;
public class ES3EditorUtility : Editor
{
public static void DisplayLink(string label, string url)
{
var style = ES3Editor.EditorStyle.Get;
if(GUILayout.Button(label, style.link))
Application.OpenURL(url);
var buttonRect = GUILayoutUtility.GetLastRect();
buttonRect.width = style.link.CalcSize(new GUIContent(label)).x;
EditorGUIUtility.AddCursorRect(buttonRect, MouseCursor.Link);
}
public static bool IsPrefabInAssets(UnityEngine.Object obj)
{
#if UNITY_2018_3_OR_NEWER
return PrefabUtility.IsPartOfPrefabAsset(obj);
#else
return (PrefabUtility.GetPrefabType(obj) == PrefabType.Prefab);
#endif
}
/*
* Gets all children and components from a GameObject or GameObjects.
* We create our own method for this because EditorUtility.CollectDeepHierarchy isn't thread safe in the Editor.
*/
public static IEnumerable<UnityEngine.Object> CollectDeepHierarchy(IEnumerable<GameObject> gos)
{
var deepHierarchy = new HashSet<UnityEngine.Object>();
foreach (var go in gos)
{
deepHierarchy.Add(go);
deepHierarchy.UnionWith(go.GetComponents<Component>());
foreach (Transform t in go.transform)
deepHierarchy.UnionWith( CollectDeepHierarchy( new GameObject[] { t.gameObject } ) );
}
return deepHierarchy;
}
[MenuItem("Tools/Easy Save 3/Getting Started...", false, 0)]
public static void DisplayGettingStarted()
{
Application.OpenURL("https://docs.moodkie.com/easy-save-3/getting-started/");
}
[MenuItem("Tools/Easy Save 3/Manual...", false, 0)]
public static void DisplayManual()
{
Application.OpenURL("https://docs.moodkie.com/product/easy-save-3/");
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 0efb8383db0883342b139a5d934554e9
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,43 @@
using UnityEditor;
using UnityEngine;
namespace ES3Internal
{
[CustomEditor(typeof(ES3GameObject))]
public class ES3GameObjectEditor : Editor
{
public override void OnInspectorGUI()
{
if (target == null)
return;
var es3Go = (ES3GameObject)target;
EditorGUILayout.HelpBox("This Component allows you to choose which Components are saved when this GameObject is saved using code.", MessageType.Info);
if (es3Go.GetComponent<ES3AutoSave>() != null)
{
EditorGUILayout.HelpBox("This Component cannot be used on GameObjects which are already managed by Auto Save.", MessageType.Error);
return;
}
foreach (var component in es3Go.GetComponents<Component>())
{
var markedToBeSaved = es3Go.components.Contains(component);
var newMarkedToBeSaved = EditorGUILayout.Toggle(component.GetType().Name, markedToBeSaved);
if(markedToBeSaved && !newMarkedToBeSaved)
{
Undo.RecordObject(es3Go, "Marked Component to save");
es3Go.components.Remove(component);
}
if (!markedToBeSaved && newMarkedToBeSaved)
{
Undo.RecordObject(es3Go, "Unmarked Component to save");
es3Go.components.Add(component);
}
}
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: e8cf79807bd2a5f438f581a4539fb4ce
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,91 @@
#if !ES3GLOBAL_DISABLED
using UnityEditor;
using UnityEngine;
using UnityEngine.SceneManagement;
using System;
using System.Collections;
using System.Collections.Generic;
namespace ES3Internal
{
[CustomEditor(typeof(ES3Internal.ES3GlobalReferences))]
[System.Serializable]
public class ES3GlobalReferencesEditor : Editor
{
private bool isDraggingOver = false;
private bool openReferences = false;
private ES3Internal.ES3GlobalReferences _globalRefs = null;
private ES3Internal.ES3GlobalReferences globalRefs
{
get
{
if (_globalRefs == null)
_globalRefs = (ES3Internal.ES3GlobalReferences)serializedObject.targetObject;
return _globalRefs;
}
}
public override void OnInspectorGUI()
{
EditorGUILayout.HelpBox("This stores references to objects in Assets, allowing them to be referenced with the same ID between scenes.", MessageType.Info);
if (EditorGUILayout.Foldout(openReferences, "References") != openReferences)
{
openReferences = !openReferences;
if (openReferences == true)
openReferences = EditorUtility.DisplayDialog("Are you sure?", "Opening this list will display every reference in the manager, which for larger projects can cause the Editor to freeze\n\nIt is strongly recommended that you save your project before continuing.", "Open References", "Cancel");
}
// Make foldout drag-and-drop enabled for objects.
if (GUILayoutUtility.GetLastRect().Contains(Event.current.mousePosition))
{
Event evt = Event.current;
switch (evt.type)
{
case EventType.DragUpdated:
case EventType.DragPerform:
isDraggingOver = true;
break;
case EventType.DragExited:
isDraggingOver = false;
break;
}
if (isDraggingOver)
{
DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
if (evt.type == EventType.DragPerform)
{
DragAndDrop.AcceptDrag();
Undo.RecordObject(globalRefs, "Add References to Easy Save 3 Reference List");
foreach (UnityEngine.Object obj in DragAndDrop.objectReferences)
globalRefs.GetOrAdd(obj);
// Return now because otherwise we'll change the GUI during an event which doesn't allow it.
return;
}
}
}
if (openReferences)
{
EditorGUI.indentLevel++;
foreach (var kvp in globalRefs.refId)
{
EditorGUILayout.BeginHorizontal();
EditorGUILayout.ObjectField(kvp.Key, typeof(UnityEngine.Object), true);
EditorGUILayout.LongField(kvp.Value);
EditorGUILayout.EndHorizontal();
}
EditorGUI.indentLevel--;
}
}
}
}
#endif

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: f331a378246ab414d8886ef5606bddd7
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,14 @@
using UnityEditor;
using UnityEngine;
using UnityEngine.SceneManagement;
using System;
using System.Collections;
[CustomEditor(typeof(ES3InspectorInfo))]
public class ES3InspectorInfoEditor : Editor
{
public override void OnInspectorGUI()
{
EditorGUILayout.HelpBox(((ES3InspectorInfo)target).message, MessageType.Info);
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: faeb2caf234951943af34ce40f17fac0
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,803 @@
#if PLAYMAKER_1_8_OR_NEWER
using UnityEngine;
using UnityEditor;
using HutongGames.PlayMaker;
using HutongGames.PlayMaker.Actions;
using HutongGames.PlayMakerEditor;
using System.Text.RegularExpressions;
namespace ES3PlayMaker
{
#region Base Actions
public abstract class BaseEditor : CustomActionEditor
{
bool showErrorHandling = false;
public abstract void DrawGUI();
public override bool OnGUI()
{
DrawGUI();
EditorGUILayout.Separator();
showErrorHandling = EditorGUILayout.Foldout(showErrorHandling, "Error Handling");
if (showErrorHandling)
{
EditorGUI.indentLevel++;
EditField("errorEvent");
EditField("errorMessage");
EditorGUI.indentLevel--;
}
return GUI.changed;
}
// Displays the FsmVar field without the unnecessary Type field.
protected void FsmVarField(string fieldName)
{
if (target == null || target.State == null)
return;
var fsmVar = (FsmVar)ES3Internal.ES3Reflection.GetField(target.GetType(), fieldName).GetValue(target);
if (fsmVar == null)
{
fsmVar = new FsmVar();
ES3Internal.ES3Reflection.GetField(target.GetType(), fieldName).SetValue(target, fsmVar);
}
EditorGUILayout.BeginHorizontal();
var label = Regex.Replace(fieldName, @"\p{Lu}", m => " " + m.Value.ToLowerInvariant());
EditorGUILayout.PrefixLabel(char.ToUpperInvariant(label[0]) + label.Substring(1));
var localVariables = target.Fsm.Variables.GetAllNamedVariablesSorted();
var globalVariables = FsmVariables.GlobalVariables.GetAllNamedVariablesSorted();
var variableNames = new string[localVariables.Length + globalVariables.Length];
int selected = -1;
for(int i=0; i<variableNames.Length; i++)
{
var variable = i >= localVariables.Length ? globalVariables[i - localVariables.Length] : localVariables[i];
variableNames[i] = i >= localVariables.Length ? "Globals/"+variable.Name : variable.Name;
if (fsmVar.NamedVar == variable)
selected = i;
}
var newSelected = EditorGUILayout.Popup(selected, variableNames);
EditorGUILayout.EndHorizontal();
if (newSelected == -1)
return;
if (selected != newSelected)
{
if (newSelected >= localVariables.Length)
fsmVar.NamedVar = globalVariables[newSelected - localVariables.Length];
else
fsmVar.NamedVar = localVariables[newSelected];
}
}
}
public abstract class SettingsEditor : BaseEditor
{
public override bool OnGUI()
{
base.OnGUI();
return DrawSettingsEditor();
}
public bool DrawSettingsEditor()
{
var action = target as ES3PlayMaker.SettingsAction;
if (action == null)
return false;
action.overrideDefaultSettings.Value = EditorGUILayout.ToggleLeft("Override Default Settings", action.overrideDefaultSettings.Value);
if (action.overrideDefaultSettings.Value)
{
EditorGUI.indentLevel++;
EditField("path");
EditField("location");
EditField("encryptionType");
EditField("encryptionPassword");
EditField("compressionType");
EditField("directory");
EditField("format");
EditField("bufferSize");
EditorGUI.indentLevel--;
EditorGUILayout.Space();
}
return GUI.changed;
}
}
public abstract class KeyValueSettingsEditor : SettingsEditor
{
public override bool OnGUI()
{
EditField("key");
EditField("value");
base.OnGUI();
return GUI.changed;
}
public override void DrawGUI(){}
}
public abstract class ES3FileActionEditor : BaseEditor
{
public override bool OnGUI()
{
EditField("fsmES3File");
base.OnGUI();
var action = target as ES3PlayMaker.ES3FileAction;
if (action == null)
return false;
return GUI.changed;
}
}
#endregion
#if !PLAYMAKER_1_9_OR_NEWER
#region Save Actions
/*[CustomActionEditor(typeof(ES3PlayMaker.Save))]
public class SaveEditor : KeyValueSettingsEditor{}*/
/*[CustomActionEditor(typeof(ES3PlayMaker.SaveMultiple))]
public class SaveMultipleEditor : SettingsEditor
{
public override bool OnGUI()
{
return base.OnGUI();
}
public override void DrawGUI()
{
DrawDefaultInspector();
}
}*/
[CustomActionEditor(typeof(ES3PlayMaker.SaveAll))]
public class SaveAllEditor : SettingsEditor
{
public override void DrawGUI()
{
EditField("key");
EditField("saveFsmVariables");
EditField("saveGlobalVariables");
}
}
[CustomActionEditor(typeof(ES3PlayMaker.SaveRaw))]
public class SaveRawEditor : SettingsEditor
{
public override void DrawGUI()
{
EditField("str");
EditField("useBase64Encoding");
EditField("appendNewline");
}
}
[CustomActionEditor(typeof(ES3PlayMaker.AppendRaw))]
public class AppendRawEditor : SettingsEditor
{
public override void DrawGUI()
{
EditField("str");
EditField("useBase64Encoding");
EditField("appendNewline");
}
}
[CustomActionEditor(typeof(ES3PlayMaker.SaveImage))]
public class SaveImageEditor : SettingsEditor
{
public override void DrawGUI()
{
EditField("imagePath");
EditField("texture2D");
EditField("quality");
}
}
#endregion
#region Load Actions
[CustomActionEditor(typeof(ES3PlayMaker.Load))]
public class LoadEditor : KeyValueSettingsEditor
{
public override void DrawGUI()
{
EditorGUILayout.Space();
EditField("defaultValue");
}
}
[CustomActionEditor(typeof(ES3PlayMaker.LoadInto))]
public class LoadIntoEditor : KeyValueSettingsEditor{}
[CustomActionEditor(typeof(ES3PlayMaker.LoadAll))]
public class LoadAllEditor : SettingsEditor
{
public override void DrawGUI()
{
EditField("key");
EditField("loadFsmVariables");
EditField("loadGlobalVariables");
}
}
[CustomActionEditor(typeof(ES3PlayMaker.LoadAudio))]
public class LoadAudioEditor : SettingsEditor
{
public override void DrawGUI()
{
EditField("audioFilePath");
EditField("audioClip");
#if UNITY_2018_3_OR_NEWER
EditField("audioType");
#endif
}
}
[CustomActionEditor(typeof(ES3PlayMaker.LoadImage))]
public class LoadImageEditor : SettingsEditor
{
public override void DrawGUI()
{
EditField("imagePath");
EditField("texture2D");
}
}
[CustomActionEditor(typeof(ES3PlayMaker.LoadRawString))]
public class LoadRawStringEditor : SettingsEditor
{
public override void DrawGUI()
{
EditField("str");
EditField("useBase64Encoding");
}
}
#endregion
#region Exists Actions
[CustomActionEditor(typeof(ES3PlayMaker.KeyExists))]
public class KeyExistsEditor : SettingsEditor
{
public override void DrawGUI()
{
EditField("key");
EditField("exists");
EditorGUILayout.Separator();
EditField("existsEvent");
EditField("doesNotExistEvent");
}
}
[CustomActionEditor(typeof(ES3PlayMaker.FileExists))]
public class FileExistsEditor : SettingsEditor
{
public override void DrawGUI()
{
EditField("filePath");
EditField("exists");
EditorGUILayout.Separator();
EditField("existsEvent");
EditField("doesNotExistEvent");
}
}
[CustomActionEditor(typeof(ES3PlayMaker.DirectoryExists))]
public class DirectoryExistsEditor : SettingsEditor
{
public override void DrawGUI()
{
EditField("directoryPath");
EditField("exists");
EditorGUILayout.Separator();
EditField("existsEvent");
EditField("doesNotExistEvent");
}
}
#endregion
#region Delete Actions
[CustomActionEditor(typeof(ES3PlayMaker.DeleteKey))]
public class DeleteKeyEditor : SettingsEditor
{
public override void DrawGUI()
{
EditField("key");
}
}
[CustomActionEditor(typeof(ES3PlayMaker.DeleteFile))]
public class DeleteFileEditor : SettingsEditor
{
public override void DrawGUI()
{
EditField("filePath");
}
}
[CustomActionEditor(typeof(ES3PlayMaker.DeleteDirectory))]
public class DeleteDirectoryEditor : SettingsEditor
{
public override void DrawGUI()
{
EditField("directoryPath");
}
}
#endregion
#region Backup Actions
[CustomActionEditor(typeof(ES3PlayMaker.CreateBackup))]
public class CreateBackupEditor : SettingsEditor
{
public override void DrawGUI()
{
EditField("filePath");
}
}
[CustomActionEditor(typeof(ES3PlayMaker.RestoreBackup))]
public class RestoreBackupEditor : SettingsEditor
{
public override void DrawGUI()
{
EditField("filePath");
EditField("backupWasRestored");
}
}
#endregion
#region Key, File and Directory methods
[CustomActionEditor(typeof(ES3PlayMaker.RenameFile))]
public class RenameFileEditor : SettingsEditor
{
public override void DrawGUI()
{
EditField("oldFilePath");
EditField("newFilePath");
}
}
[CustomActionEditor(typeof(ES3PlayMaker.CopyFile))]
public class CopyFileEditor : SettingsEditor
{
public override void DrawGUI()
{
EditField("oldFilePath");
EditField("newFilePath");
}
}
[CustomActionEditor(typeof(ES3PlayMaker.CopyDirectory))]
public class CopyDirectoryEditor : SettingsEditor
{
public override void DrawGUI()
{
EditField("oldDirectoryPath");
EditField("newDirectoryPath");
}
}
[CustomActionEditor(typeof(ES3PlayMaker.GetKeys))]
public class GetKeysEditor : SettingsEditor
{
public override void DrawGUI()
{
EditField("filePath");
EditField("keys");
}
}
[CustomActionEditor(typeof(ES3PlayMaker.GetKeyCount))]
public class GetKeyCountEditor : SettingsEditor
{
public override void DrawGUI()
{
EditField("filePath");
EditField("keyCount");
}
}
[CustomActionEditor(typeof(ES3PlayMaker.GetFiles))]
public class GetFilesEditor : SettingsEditor
{
public override void DrawGUI()
{
EditField("directoryPath");
EditField("files");
}
}
[CustomActionEditor(typeof(ES3PlayMaker.GetDirectories))]
public class GetDirectoriesEditor : SettingsEditor
{
public override void DrawGUI()
{
EditField("directoryPath");
EditField("directories");
}
}
#endregion
#region ES3File Actions
[CustomActionEditor(typeof(ES3PlayMaker.ES3FileCreate))]
public class ES3FileCreateEditor : SettingsEditor
{
public override void DrawGUI()
{
EditField("fsmES3File");
EditField("filePath");
EditField("syncWithFile");
}
}
[CustomActionEditor(typeof(ES3PlayMaker.ES3FileSync))]
public class ES3FileSyncEditor : SettingsEditor
{
public override void DrawGUI()
{
EditField("fsmES3File");
}
}
/*[CustomActionEditor(typeof(ES3PlayMaker.ES3FileSave))]
public class ES3FileSaveEditor : SaveEditor
{
public override void DrawGUI()
{
EditField("fsmES3File");
base.DrawGUI();
}
}*/
[CustomActionEditor(typeof(ES3PlayMaker.ES3FileLoad))]
public class ES3FileLoadEditor : LoadEditor
{
public override void DrawGUI()
{
EditField("fsmES3File");
base.DrawGUI();
}
}
[CustomActionEditor(typeof(ES3PlayMaker.ES3FileLoadInto))]
public class ES3FileLoadIntoEditor : LoadIntoEditor
{
public override void DrawGUI()
{
base.DrawGUI();
EditField("fsmES3File");
}
}
[CustomActionEditor(typeof(ES3PlayMaker.ES3FileDeleteKey))]
public class ES3FileDeleteKeyEditor : DeleteKeyEditor
{
public override void DrawGUI()
{
base.DrawGUI();
EditField("fsmES3File");
}
}
[CustomActionEditor(typeof(ES3PlayMaker.ES3FileKeyExists))]
public class ES3FileKeyExistsEditor : KeyExistsEditor
{
public override void DrawGUI()
{
EditField("fsmES3File");
base.DrawGUI();
}
}
[CustomActionEditor(typeof(ES3PlayMaker.ES3FileGetKeys))]
public class ES3FileGetKeysEditor : ES3FileActionEditor
{
public override void DrawGUI()
{
EditField("keys");
}
}
[CustomActionEditor(typeof(ES3PlayMaker.ES3FileClear))]
public class ES3FileClearEditor : BaseEditor
{
public override void DrawGUI()
{
EditField("fsmES3File");
}
}
[CustomActionEditor(typeof(ES3PlayMaker.ES3FileSize))]
public class ES3FileSizeEditor : BaseEditor
{
public override void DrawGUI()
{
EditField("size");
EditField("fsmES3File");
}
}
#endregion
#region ES3Cloud Actions
#if !DISABLE_WEB
public abstract class ES3CloudEditor : SettingsEditor
{
protected abstract void DrawChildGUI();
public override void DrawGUI()
{
EditField("url");
EditField("apiKey");
EditorGUILayout.Space();
DrawChildGUI();
EditorGUILayout.Space();
EditField("errorCode");
}
}
public abstract class ES3CloudUserEditor : ES3CloudEditor
{
public bool showUser = false;
protected override void DrawChildGUI()
{
if((showUser = EditorGUILayout.Foldout(showUser, "User (optional)")))
{
EditorGUI.indentLevel++;
EditField("user");
EditField("password");
EditorGUI.indentLevel--;
}
}
}
[CustomActionEditor(typeof(ES3PlayMaker.ES3CloudSync))]
public class ES3CloudSyncEditor : ES3CloudUserEditor
{
protected override void DrawChildGUI()
{
EditField("path");
base.DrawChildGUI();
}
}
[CustomActionEditor(typeof(ES3PlayMaker.ES3CloudDownloadFile))]
public class ES3CloudDownloadFileEditor : ES3CloudUserEditor
{
protected override void DrawChildGUI()
{
EditField("path");
base.DrawChildGUI();
}
}
[CustomActionEditor(typeof(ES3PlayMaker.ES3CloudDownloadES3File))]
public class ES3CloudDownloadES3FileEditor : BaseEditor
{
public bool showUser = false;
public override void DrawGUI()
{
EditField("fsmES3File");
EditField("url");
EditField("apiKey");
EditField("errorCode");
if ((showUser = EditorGUILayout.Foldout(showUser, "User (optional)")))
{
EditorGUI.indentLevel++;
EditField("user");
EditField("password");
EditorGUI.indentLevel--;
}
}
}
[CustomActionEditor(typeof(ES3PlayMaker.ES3CloudUploadFile))]
public class ES3CloudUploadFileEditor : ES3CloudUserEditor
{
protected override void DrawChildGUI()
{
EditField("path");
base.DrawChildGUI();
}
}
[CustomActionEditor(typeof(ES3PlayMaker.ES3CloudUploadES3File))]
public class ES3CloudUploadES3FileEditor : BaseEditor
{
public bool showUser = false;
public override void DrawGUI()
{
EditField("fsmES3File");
EditField("url");
EditField("apiKey");
EditField("errorCode");
if((showUser = EditorGUILayout.Foldout(showUser, "User (optional)")))
{
EditorGUI.indentLevel++;
EditField("user");
EditField("password");
EditorGUI.indentLevel--;
}
}
}
[CustomActionEditor(typeof(ES3PlayMaker.ES3CloudDeleteFile))]
public class ES3CloudDeleteFileEditor : ES3CloudUserEditor
{
protected override void DrawChildGUI()
{
EditField("path");
base.DrawChildGUI();
}
}
[CustomActionEditor(typeof(ES3PlayMaker.ES3CloudRenameFile))]
public class ES3CloudRenameFileEditor : ES3CloudUserEditor
{
protected override void DrawChildGUI()
{
EditField("path");
EditField("newFilename");
base.DrawChildGUI();
}
}
[CustomActionEditor(typeof(ES3PlayMaker.ES3CloudDownloadFilenames))]
public class ES3CloudDownloadFilenamesEditor : ES3CloudUserEditor
{
protected override void DrawChildGUI()
{
EditField("filenames");
EditField("searchPattern");
base.DrawChildGUI();
}
}
[CustomActionEditor(typeof(ES3PlayMaker.ES3CloudSearchFilenames))]
public class ES3CloudSearchFilenamesEditor : ES3CloudUserEditor
{
protected override void DrawChildGUI()
{
EditField("filenames");
EditField("searchPattern");
base.DrawChildGUI();
}
}
[CustomActionEditor(typeof(ES3PlayMaker.ES3CloudDownloadTimestamp))]
public class ES3CloudDownloadTimestampEditor : ES3CloudUserEditor
{
protected override void DrawChildGUI()
{
EditField("path");
EditField("timestamp");
base.DrawChildGUI();
}
}
#endif
#endregion
#region ES3SpreadsheetActions
[CustomActionEditor(typeof(ES3PlayMaker.ES3SpreadsheetCreate))]
public class ES3SpreadsheetCreateEditor : BaseEditor
{
public override void DrawGUI()
{
EditField("fsmES3Spreadsheet");
}
}
[CustomActionEditor(typeof(ES3PlayMaker.ES3SpreadsheetSetCell))]
public class ES3SpreadsheetSetCellEditor : BaseEditor
{
public override void DrawGUI()
{
EditField("fsmES3Spreadsheet");
EditField("col");
EditField("row");
EditField("value");
}
}
[CustomActionEditor(typeof(ES3PlayMaker.ES3SpreadsheetGetCell))]
public class ES3SpreadsheetGetCellEditor : BaseEditor
{
public override void DrawGUI()
{
EditField("fsmES3Spreadsheet");
EditField("col");
EditField("row");
EditField("value");
}
}
[CustomActionEditor(typeof(ES3PlayMaker.ES3SpreadsheetLoad))]
public class ES3SpreadsheetLoadEditor : SettingsEditor
{
public override void DrawGUI()
{
EditField("fsmES3Spreadsheet");
EditField("filePath");
}
}
[CustomActionEditor(typeof(ES3PlayMaker.ES3SpreadsheetSave))]
public class ES3SpreadsheetSaveEditor : SettingsEditor
{
public override void DrawGUI()
{
EditField("fsmES3Spreadsheet");
EditField("filePath");
EditField("append");
}
}
#endregion
#region Caching
[CustomActionEditor(typeof(ES3PlayMaker.CacheFile))]
public class CacheFileEditor : SettingsEditor
{
public override void DrawGUI()
{
EditField("filePath");
}
}
[CustomActionEditor(typeof(ES3PlayMaker.StoreCachedFile))]
public class StoreCachedFileEditor : SettingsEditor
{
public override void DrawGUI()
{
EditField("filePath");
}
}
#endregion
#endif
}
#endif

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 71eac37f5c1db63409906f162ac6bb74
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,272 @@
using UnityEngine;
using UnityEditor;
using UnityEditor.Callbacks;
using UnityEditor.SceneManagement;
using UnityEngine.SceneManagement;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using ES3Internal;
/*
* ---- How Postprocessing works for the reference manager ----
* - When the manager is first added to the scene, all top-level dependencies are added to the manager (AddManagerToScene).
* - When the manager is first added to the scene, all prefabs with ES3Prefab components are added to the manager (AddManagerToScene).
* - All GameObjects and Components in the scene are added to the reference manager when we enter Playmode or the scene is saved (PlayModeStateChanged, OnWillSaveAssets -> AddGameObjectsAndComponentstoManager).
* - When a UnityEngine.Object field of a Component is modified, the new UnityEngine.Object reference is added to the reference manager (PostProcessModifications)
* - All prefabs with ES3Prefab Components are added to the reference manager when we enter Playmode or the scene is saved (PlayModeStateChanged, OnWillSaveAssets -> AddGameObjectsAndComponentstoManager).
* - Local references for prefabs are processed whenever a prefab with an ES3Prefab Component is deselected (SelectionChanged -> ProcessGameObject)
*/
[InitializeOnLoad]
public class ES3Postprocessor : UnityEditor.AssetModificationProcessor
{
public static ES3ReferenceMgr RefMgr
{
get { return (ES3ReferenceMgr)ES3ReferenceMgr.Current; }
}
public static GameObject lastSelected = null;
// This constructor is also called once when playmode is activated and whenever recompilation happens
// because we have the [InitializeOnLoad] attribute assigned to the class.
static ES3Postprocessor()
{
#if UNITY_2020_2_OR_NEWER
ObjectChangeEvents.changesPublished += Changed;
#endif
ObjectFactory.componentWasAdded += ComponentWasAdded;
// Open the Easy Save 3 window the first time ES3 is installed.
//ES3Editor.ES3Window.OpenEditorWindowOnStart();
EditorApplication.playModeStateChanged -= PlayModeStateChanged;
EditorApplication.playModeStateChanged += PlayModeStateChanged;
EditorSceneManager.sceneOpened += OnSceneOpened;
}
#region Reference Updating
private static void PlayModeStateChanged(PlayModeStateChange state)
{
if (state == PlayModeStateChange.ExitingEditMode)
UpdateAssembliesContainingES3Types();
}
private static void OnSceneOpened(Scene scene, OpenSceneMode mode)
{
if (mode == OpenSceneMode.AdditiveWithoutLoading || Application.isPlaying)
return;
if (ES3Settings.defaultSettingsScriptableObject.autoUpdateReferences && ES3Settings.defaultSettingsScriptableObject.updateReferencesWhenSceneIsOpened)
RefreshScene(scene);
}
private static void RefreshReferences(bool isEnteringPlayMode = false)
{
/*if (refreshed) // If we've already refreshed, do nothing.
return;*/
if (ES3Settings.defaultSettingsScriptableObject.autoUpdateReferences)
for (int i = 0; i < SceneManager.sceneCount; i++)
RefreshScene(SceneManager.GetSceneAt(i));
//refreshed = true;
}
static void RefreshScene(Scene scene, bool isEnteringPlayMode = false)
{
if (scene != null && scene.isLoaded)
{
var mgr = (ES3ReferenceMgr)ES3ReferenceMgr.GetManagerFromScene(scene);
if (mgr != null)
mgr.RefreshDependencies(isEnteringPlayMode);
}
}
static void ComponentWasAdded(Component c)
{
var scene = c.gameObject.scene;
if (!scene.isLoaded)
return;
var mgr = (ES3ReferenceMgr)ES3ReferenceMgr.GetManagerFromScene(scene);
if (mgr != null)
mgr.AddDependencies(c);
}
#if UNITY_2020_2_OR_NEWER
static void Changed(ref ObjectChangeEventStream stream)
{
if (EditorApplication.isUpdating || Application.isPlaying || !ES3Settings.defaultSettingsScriptableObject.autoUpdateReferences || !ES3Settings.defaultSettingsScriptableObject.updateReferencesWhenSceneChanges)
return;
for (int i = 0; i < stream.length; i++)
{
var eventType = stream.GetEventType(i);
int[] instanceIds;
Scene scene;
if (eventType == ObjectChangeKind.ChangeGameObjectOrComponentProperties)
{
ChangeGameObjectOrComponentPropertiesEventArgs evt;
stream.GetChangeGameObjectOrComponentPropertiesEvent(i, out evt);
instanceIds = new int[] { evt.instanceId };
scene = evt.scene;
}
else if (eventType == ObjectChangeKind.CreateGameObjectHierarchy)
{
CreateGameObjectHierarchyEventArgs evt;
stream.GetCreateGameObjectHierarchyEvent(i, out evt);
instanceIds = new int[] { evt.instanceId };
scene = evt.scene;
}
/*else if (eventType == ObjectChangeKind.ChangeAssetObjectProperties)
{
ChangeAssetObjectPropertiesEventArgs evt;
stream.GetChangeAssetObjectPropertiesEvent(i, out evt);
instanceIds = new int[] { evt.instanceId };
}*/
else if (eventType == ObjectChangeKind.UpdatePrefabInstances)
{
UpdatePrefabInstancesEventArgs evt;
stream.GetUpdatePrefabInstancesEvent(i, out evt);
instanceIds = evt.instanceIds.ToArray();
scene = evt.scene;
}
else
continue;
var mgr = (ES3ReferenceMgr)ES3ReferenceMgr.GetManagerFromScene(scene);
if (mgr == null)
return;
foreach (var id in instanceIds)
{
try
{
var obj = EditorUtility.InstanceIDToObject(id);
if (obj == null)
continue;
mgr.AddDependencies(obj);
}
catch { }
}
}
}
#endif
/*public static void PlayModeStateChanged(PlayModeStateChange state)
{
// Add all GameObjects and Components to the reference manager before we enter play mode.
if (state == PlayModeStateChange.ExitingEditMode && ES3Settings.defaultSettingsScriptableObject.autoUpdateReferences)
RefreshReferences(true);
}*/
public static string[] OnWillSaveAssets(string[] paths)
{
// Don't refresh references when the application is playing.
if (!EditorApplication.isUpdating && !Application.isPlaying)
{
if(ES3Settings.defaultSettingsScriptableObject.autoUpdateReferences && ES3Settings.defaultSettingsScriptableObject.updateReferencesWhenSceneIsSaved)
RefreshReferences();
UpdateAssembliesContainingES3Types();
}
return paths;
}
#endregion
private static void UpdateAssembliesContainingES3Types()
{
var assemblies = UnityEditor.Compilation.CompilationPipeline.GetAssemblies();
if (assemblies == null || assemblies.Length == 0)
return;
var defaults = ES3Settings.defaultSettingsScriptableObject;
var currentAssemblyNames = defaults.settings.assemblyNames;
var assemblyNames = new List<string>();
foreach (var assembly in assemblies)
{
// Don't include Editor assemblies.
if (assembly.flags.HasFlag(UnityEditor.Compilation.AssemblyFlags.EditorAssembly))
continue;
// Assemblies beginning with 'com.' are assumed to be internal.
if (assembly.name.StartsWith("com."))
continue;
// If this assembly begins with 'Unity', but isn't created from an Assembly Definition File, skip it.
if (assembly.name.StartsWith("Unity"))
{
bool isAssemblyDefinition = true;
foreach (string sourceFile in assembly.sourceFiles)
{
if (!sourceFile.StartsWith("Assets/"))
{
isAssemblyDefinition = false;
break;
}
}
if (!isAssemblyDefinition)
continue;
}
assemblyNames.Add(assembly.name);
}
// If there are no assembly names,
if (assemblyNames.Count == 0)
return;
// Sort it alphabetically so that the order isn't constantly changing, which can affect version control.
assemblyNames.Sort();
// Only update if the list has changed.
for (int i = 0; i < assemblyNames.Count; i++)
{
if (currentAssemblyNames.Length != assemblyNames.Count || currentAssemblyNames[i] != assemblyNames[i])
{
defaults.settings.assemblyNames = assemblyNames.ToArray();
EditorUtility.SetDirty(defaults);
break;
}
}
}
public static GameObject AddManagerToScene()
{
GameObject mgr = null;
if (RefMgr != null)
mgr = RefMgr.gameObject;
if (mgr == null)
mgr = new GameObject("Easy Save 3 Manager");
if (mgr.GetComponent<ES3ReferenceMgr>() == null)
{
mgr.AddComponent<ES3ReferenceMgr>();
if (!Application.isPlaying && ES3Settings.defaultSettingsScriptableObject.autoUpdateReferences)
RefMgr.RefreshDependencies();
}
if (mgr.GetComponent<ES3AutoSaveMgr>() == null)
mgr.AddComponent<ES3AutoSaveMgr>();
Undo.RegisterCreatedObjectUndo(mgr, "Enabled Easy Save for Scene");
return mgr;
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: c61f2f67a29443843be032bd952c27d0
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,50 @@
using UnityEditor;
using UnityEngine;
using UnityEngine.SceneManagement;
using System;
using System.Collections;
using ES3Internal;
[CustomEditor(typeof(ES3Prefab))]
[System.Serializable]
public class ES3PrefabEditor : Editor
{
bool showAdvanced = false;
bool openLocalRefs = false;
public override void OnInspectorGUI()
{
var es3Prefab = (ES3Prefab)serializedObject.targetObject;
EditorGUILayout.HelpBox("Easy Save is enabled for this prefab, and can be saved and loaded with the ES3 methods.", MessageType.None);
showAdvanced = EditorGUILayout.Foldout(showAdvanced, "Advanced Settings");
if(showAdvanced)
{
EditorGUI.indentLevel++;
es3Prefab.prefabId = EditorGUILayout.LongField("Prefab ID", es3Prefab.prefabId);
EditorGUILayout.LabelField("Reference count", es3Prefab.localRefs.Count.ToString());
EditorGUI.indentLevel--;
openLocalRefs = EditorGUILayout.Foldout(openLocalRefs, "localRefs");
if (openLocalRefs)
{
EditorGUI.indentLevel++;
EditorGUILayout.LabelField("It is not recommended to manually modify these.");
foreach (var kvp in es3Prefab.localRefs)
{
EditorGUILayout.BeginHorizontal();
EditorGUILayout.ObjectField(kvp.Key, typeof(UnityEngine.Object), false);
EditorGUILayout.LongField(kvp.Value);
EditorGUILayout.EndHorizontal();
}
EditorGUI.indentLevel--;
}
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: c27522c7110125a4381539571a648c7f
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,219 @@
using UnityEditor;
using UnityEngine;
using UnityEngine.SceneManagement;
using System;
using System.Collections;
using System.Collections.Generic;
[CustomEditor(typeof(ES3ReferenceMgr))]
[System.Serializable]
public class ES3ReferenceMgrEditor : Editor
{
private bool isDraggingOver = false;
private bool openReferences = false;
private ES3ReferenceMgr _mgr = null;
private ES3ReferenceMgr mgr
{
get
{
if (_mgr == null)
_mgr = (ES3ReferenceMgr)serializedObject.targetObject;
return _mgr;
}
}
public override void OnInspectorGUI()
{
EditorGUILayout.HelpBox("This allows Easy Save to maintain references to objects in your scene.\n\nIt is automatically updated when you enter Playmode or build your project.", MessageType.Info);
if (EditorGUILayout.Foldout(openReferences, "References") != openReferences)
{
openReferences = !openReferences;
if (openReferences == true)
openReferences = EditorUtility.DisplayDialog("Are you sure?", "Opening this list will display every reference in the manager, which for larger projects can cause the Editor to freeze\n\nIt is strongly recommended that you save your project before continuing.", "Open References", "Cancel");
}
// Make foldout drag-and-drop enabled for objects.
if (GUILayoutUtility.GetLastRect().Contains(Event.current.mousePosition))
{
Event evt = Event.current;
switch (evt.type)
{
case EventType.DragUpdated:
case EventType.DragPerform:
isDraggingOver = true;
break;
case EventType.DragExited:
isDraggingOver = false;
break;
}
if (isDraggingOver)
{
DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
if (evt.type == EventType.DragPerform)
{
DragAndDrop.AcceptDrag();
Undo.RecordObject(mgr, "Add References to Easy Save 3 Reference List");
foreach (UnityEngine.Object obj in DragAndDrop.objectReferences)
mgr.Add(obj);
// Return now because otherwise we'll change the GUI during an event which doesn't allow it.
return;
}
}
}
if (openReferences)
{
EditorGUI.indentLevel++;
foreach (var kvp in mgr.idRef)
{
EditorGUILayout.BeginHorizontal();
var value = EditorGUILayout.ObjectField(kvp.Value, typeof(UnityEngine.Object), true);
var key = EditorGUILayout.LongField(kvp.Key);
EditorGUILayout.EndHorizontal();
if (value != kvp.Value || key != kvp.Key)
{
Undo.RecordObject(mgr, "Change Easy Save 3 References");
// If we're deleting a value, delete it.
if (value == null)
mgr.Remove(key);
// Else, update the ID.
else
mgr.ChangeId(kvp.Key, key);
// Break, as removing or changing Dictionary items will make the foreach out of sync.
break;
}
}
EditorGUI.indentLevel--;
}
mgr.openPrefabs = EditorGUILayout.Foldout(mgr.openPrefabs, "ES3Prefabs");
if (mgr.openPrefabs)
{
EditorGUI.indentLevel++;
foreach (var prefab in mgr.prefabs)
{
EditorGUILayout.BeginHorizontal();
EditorGUILayout.ObjectField(prefab, typeof(UnityEngine.Object), true);
EditorGUILayout.EndHorizontal();
}
EditorGUI.indentLevel--;
}
var sp = serializedObject.FindProperty("excludeObjects");
EditorGUILayout.PropertyField(sp);
serializedObject.ApplyModifiedProperties();
EditorGUILayout.LabelField("Reference count", mgr.refId.Count.ToString());
EditorGUILayout.LabelField("Prefab count", mgr.prefabs.Count.ToString());
if (GUILayout.Button("Refresh"))
{
mgr.RefreshDependencies();
}
if (GUILayout.Button("Optimize"))
{
mgr.Optimize();
}
}
[MenuItem("GameObject/Easy Save 3/Add Reference(s) to Manager", false, 33)]
[MenuItem("Assets/Easy Save 3/Add Reference(s) to Manager", false, 33)]
public static void AddReferenceToManager()
{
var mgr = ES3ReferenceMgr.Current;
if (mgr == null)
{
EditorUtility.DisplayDialog("Could not add reference to manager", "This object could not be added to the reference manager because no reference manager exists in this scene. To create one, go to Tools > Easy Save 3 > Add Manager to Scene", "Ok");
return;
}
var selected = Selection.GetFiltered<UnityEngine.Object>(SelectionMode.DeepAssets);
if (selected == null || selected.Length == 0)
return;
Undo.RecordObject(mgr, "Update Easy Save 3 Reference Manager");
foreach (var obj in selected)
{
if (obj == null)
continue;
if (obj.GetType() == typeof(GameObject))
{
var go = (GameObject)obj;
if (ES3EditorUtility.IsPrefabInAssets(go) && go.GetComponent<ES3Internal.ES3Prefab>() != null)
mgr.AddPrefab(go.GetComponent<ES3Internal.ES3Prefab>());
}
((ES3ReferenceMgr)mgr).AddDependencies(obj);
}
}
[MenuItem("GameObject/Easy Save 3/Add Reference(s) to Manager", true, 33)]
[MenuItem("Assets/Easy Save 3/Add Reference(s) to Manager", true, 33)]
private static bool CanAddReferenceToManager()
{
var selected = Selection.GetFiltered<UnityEngine.Object>(SelectionMode.Deep);
return selected != null && selected.Length > 0 && ES3ReferenceMgr.Current != null;
}
[MenuItem("GameObject/Easy Save 3/Exclude Reference(s) from Manager", false, 33)]
[MenuItem("Assets/Easy Save 3/Exclude Reference(s) from Manager", false, 33)]
public static void ExcludeReferenceFromManager()
{
var mgr = (ES3ReferenceMgr)ES3ReferenceMgr.Current;
if (mgr == null)
{
EditorUtility.DisplayDialog("Could not exclude reference from manager", "This object could not be excluded from the reference manager because no reference manager exists in this scene. To create one, go to Tools > Easy Save 3 > Add Manager to Scene", "Ok");
return;
}
var selected = Selection.GetFiltered<UnityEngine.Object>(SelectionMode.DeepAssets);
if (selected == null || selected.Length == 0)
return;
Undo.RecordObject(mgr, "Exclude from Easy Save 3 Reference Manager");
if (mgr.excludeObjects == null)
mgr.excludeObjects = new List<UnityEngine.Object>();
mgr.excludeObjects.AddRange(EditorUtility.CollectDependencies(selected));
mgr.RemoveNullOrInvalidValues();
}
[MenuItem("GameObject/Easy Save 3/Add Manager to Scene", false, 33)]
[MenuItem("Assets/Easy Save 3/Add Manager to Scene", false, 33)]
[MenuItem("Tools/Easy Save 3/Add Manager to Scene", false, 150)]
public static void EnableForScene()
{
if(!SceneManager.GetActiveScene().isLoaded)
EditorUtility.DisplayDialog("Could not add manager to scene", "Could not add Easy Save 3 Manager to scene because there is not currently a scene open.", "Ok");
Selection.activeObject = ES3Postprocessor.AddManagerToScene();
}
[MenuItem("GameObject/Easy Save 3/Add Manager to Scene", true, 33)]
[MenuItem("Assets/Easy Save 3/Add Manager to Scene", true, 33)]
[MenuItem("Tools/Easy Save 3/Add Manager to Scene", true, 150)]
private static bool CanEnableForScene()
{
return ES3ReferenceMgr.GetManagerFromScene(SceneManager.GetActiveScene()) == null;
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: b7bc936fce3c29c44bdc433708cf0002
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,47 @@
using System;
using UnityEngine;
namespace ES3Types
{
[UnityEngine.Scripting.Preserve]
[ES3PropertiesAttribute([propertyNames])]
public class ES3UserType_[es3TypeSuffix] : ES3ScriptableObjectType
{
public static ES3Type Instance = null;
public ES3UserType_[es3TypeSuffix]() : base(typeof([fullType])){ Instance = this; priority = 1; }
protected override void WriteScriptableObject(object obj, ES3Writer writer)
{
var instance = ([fullType])obj;
[writes]
}
protected override void ReadScriptableObject<T>(ES3Reader reader, object obj)
{
var instance = ([fullType])obj;
foreach(string propertyName in reader.Properties)
{
switch(propertyName)
{
[reads]
default:
reader.Skip();
break;
}
}
}
}
public class ES3UserType_[es3TypeSuffix]Array : ES3ArrayType
{
public static ES3Type Instance;
public ES3UserType_[es3TypeSuffix]Array() : base(typeof([fullType][]), ES3UserType_[es3TypeSuffix].Instance)
{
Instance = this;
}
}
}

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 08a76e32a0a6e2e45950b31af2d2d6bc
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,76 @@
using UnityEditor;
using UnityEngine;
using UnityEditor.Build;
using System.Collections.Generic;
using UnityEditor.Compilation;
using System.Reflection;
using System.Linq;
using System;
[InitializeOnLoad]
public class ES3ScriptingDefineSymbols
{
static ES3ScriptingDefineSymbols()
{
SetDefineSymbols();
}
static void SetDefineSymbols()
{
if (Type.GetType("Unity.VisualScripting.IncludeInSettingsAttribute, Unity.VisualScripting.Core") != null)
SetDefineSymbol("UNITY_VISUAL_SCRIPTING");
if (Type.GetType("Ludiq.IncludeInSettingsAttribute, Ludiq.Core.Runtime") != null)
SetDefineSymbol("BOLT_VISUAL_SCRIPTING");
}
static void SetDefineSymbol(string symbol)
{
#if UNITY_2021_2_OR_NEWER
foreach (var target in GetAllNamedBuildTargets())
{
string[] defines;
try
{
PlayerSettings.GetScriptingDefineSymbols(target, out defines);
if (!defines.Contains(symbol))
{
ArrayUtility.Add(ref defines, symbol);
PlayerSettings.SetScriptingDefineSymbols(target, defines);
}
}
catch { }
}
#else
string definesString = PlayerSettings.GetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup);
var allDefines = new HashSet<string>(definesString.Split(';'));
if (!allDefines.Contains(symbol))
PlayerSettings.SetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup, string.Join(";", allDefines.Concat(new string[] { symbol }).ToArray()));
#endif
return;
}
#if UNITY_2021_2_OR_NEWER
static List<NamedBuildTarget> GetAllNamedBuildTargets()
{
var staticFields = typeof(NamedBuildTarget).GetFields(BindingFlags.Public | BindingFlags.Static);
var buildTargets = new List<NamedBuildTarget>();
foreach (var staticField in staticFields)
{
// We exclude 'Unknown' because this can throw errors when used with certain methods.
if (staticField.Name == "Unknown")
continue;
// A bug at Unity's end means that Stadia can throw an error.
if (staticField.Name == "Stadia")
continue;
if (staticField.FieldType == typeof(NamedBuildTarget))
buildTargets.Add((NamedBuildTarget)staticField.GetValue(null));
}
return buildTargets;
}
#endif
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 5905146e6373faf4f884a77dad2649dd
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,56 @@
using UnityEditor;
using UnityEngine;
using UnityEngine.SceneManagement;
using System;
using System.Collections;
using ES3Internal;
namespace ES3Editor
{
public static class ES3SettingsEditor
{
public static void Draw(ES3SerializableSettings settings)
{
var style = EditorStyle.Get;
settings.location = (ES3.Location)EditorGUILayout.EnumPopup("Location", settings.location);
// If the location is File, show the Directory.
if(settings.location == ES3.Location.File)
settings.directory = (ES3.Directory)EditorGUILayout.EnumPopup("Directory", settings.directory);
settings.path = EditorGUILayout.TextField("Default File Path", settings.path);
EditorGUILayout.Space();
settings.encryptionType = (ES3.EncryptionType)EditorGUILayout.EnumPopup("Encryption", settings.encryptionType);
settings.encryptionPassword = EditorGUILayout.TextField("Encryption Password", settings.encryptionPassword);
EditorGUILayout.Space();
settings.compressionType = (ES3.CompressionType)EditorGUILayout.EnumPopup("Compression", settings.compressionType);
EditorGUILayout.Space();
settings.saveChildren = EditorGUILayout.Toggle("Save GameObject Children", settings.saveChildren);
EditorGUILayout.Space();
if(settings.showAdvancedSettings = EditorGUILayout.Foldout(settings.showAdvancedSettings, "Advanced Settings"))
{
EditorGUILayout.BeginVertical(style.area);
settings.format = (ES3.Format)EditorGUILayout.EnumPopup("Format", settings.format);
if (settings.format == ES3.Format.JSON)
settings.prettyPrint = EditorGUILayout.Toggle(new GUIContent("Pretty print JSON"), settings.prettyPrint);
settings.bufferSize = EditorGUILayout.IntField("Buffer Size", settings.bufferSize);
settings.memberReferenceMode = (ES3.ReferenceMode)EditorGUILayout.EnumPopup("Serialise Unity Object fields", settings.memberReferenceMode);
settings.serializationDepthLimit = EditorGUILayout.IntField("Serialisation Depth", settings.serializationDepthLimit);
settings.postprocessRawCachedData = EditorGUILayout.Toggle(new GUIContent("Postprocess raw cached data"), settings.postprocessRawCachedData);
EditorGUILayout.Space();
EditorGUILayout.EndVertical();
}
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: b608a165fbf7ede4b9a4aea8d44dc089
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,55 @@
using System;
using UnityEngine;
namespace ES3Types
{
[UnityEngine.Scripting.Preserve]
[ES3PropertiesAttribute([propertyNames])]
public class ES3UserType_[es3TypeSuffix] : ES3Type
{
public static ES3Type Instance = null;
public ES3UserType_[es3TypeSuffix]() : base(typeof([fullType])){ Instance = this; priority = 1;}
public override void Write(object obj, ES3Writer writer)
{
var instance = ([fullType])obj;
[writes]
}
public override object Read<T>(ES3Reader reader)
{
var instance = new [fullType]();
ReadInto<T>(reader, instance);
return instance;
}
public override void ReadInto<T>(ES3Reader reader, object obj)
{
var instance = ([fullType])obj;
string propertyName;
while((propertyName = reader.ReadPropertyName()) != null)
{
switch(propertyName)
{
[reads]
default:
reader.Skip();
break;
}
}
}
}
public class ES3UserType_[es3TypeSuffix]Array : ES3ArrayType
{
public static ES3Type Instance;
public ES3UserType_[es3TypeSuffix]Array() : base(typeof([fullType][]), ES3UserType_[es3TypeSuffix].Instance)
{
Instance = this;
}
}
}

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 5d810f25a686f3d4ba733d4850dcb74f
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,62 @@
using System;
using UnityEngine;
namespace ES3Types
{
[UnityEngine.Scripting.Preserve]
public class ES3UserType_Material : ES3UnityObjectType
{
public static ES3Type Instance = null;
public ES3UserType_Material() : base(typeof(UnityEngine.Material)){ Instance = this; priority = 1; }
protected override void WriteUnityObject(object obj, ES3Writer writer)
{
var instance = (UnityEngine.Material)obj;
writer.WriteProperty("shader", instance.shader);
writer.WriteProperty("renderQueue", instance.renderQueue, ES3Type_int.Instance);
writer.WriteProperty("shaderKeywords", instance.shaderKeywords);
writer.WriteProperty("globalIlluminationFlags", instance.globalIlluminationFlags);
[writes]
}
protected override object ReadUnityObject<T>(ES3Reader reader)
{
var obj = new Material(Shader.Find("Diffuse"));
ReadUnityObject<T>(reader, obj);
return obj;
}
protected override void ReadUnityObject<T>(ES3Reader reader, object obj)
{
var instance = (UnityEngine.Material)obj;
foreach(string propertyName in reader.Properties)
{
switch(propertyName)
{
case "name":
instance.name = reader.Read<string>(ES3Type_string.Instance);
break;
case "shader":
instance.shader = reader.Read<UnityEngine.Shader>(ES3Type_Shader.Instance);
break;
case "renderQueue":
instance.renderQueue = reader.Read<System.Int32>(ES3Type_int.Instance);
break;
case "shaderKeywords":
instance.shaderKeywords = reader.Read<System.String[]>();
break;
case "globalIlluminationFlags":
instance.globalIlluminationFlags = reader.Read<UnityEngine.MaterialGlobalIlluminationFlags>();
break;
[reads]
default:
reader.Skip();
break;
}
}
}
}
}

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 2756c69c9bcfcbf41b720c5a9d44ff16
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,49 @@
using System;
using UnityEngine;
namespace ES3Types
{
[UnityEngine.Scripting.Preserve]
[ES3PropertiesAttribute([propertyNames])]
public class ES3UserType_[es3TypeSuffix] : ES3Type
{
public static ES3Type Instance = null;
public ES3UserType_[es3TypeSuffix]() : base(typeof([fullType])){ Instance = this; priority = 1;}
public override void Write(object obj, ES3Writer writer)
{
var instance = ([fullType])obj;
[writes]
}
public override object Read<T>(ES3Reader reader)
{
var instance = new [fullType]();
string propertyName;
while((propertyName = reader.ReadPropertyName()) != null)
{
switch(propertyName)
{
[reads]
default:
reader.Skip();
break;
}
}
return instance;
}
}
public class ES3UserType_[es3TypeSuffix]Array : ES3ArrayType
{
public static ES3Type Instance;
public ES3UserType_[es3TypeSuffix]Array() : base(typeof([fullType][]), ES3UserType_[es3TypeSuffix].Instance)
{
Instance = this;
}
}
}

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 4747441cd6669bc46a581b86208dc3c1
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,238 @@
using UnityEngine;
using UnityEditor;
using System.Linq;
namespace ES3Editor
{
public class ES3Window : EditorWindow
{
private SubWindow[] windows = null;
public SubWindow currentWindow;
[MenuItem("Window/Easy Save 3", false, 1000)]
[MenuItem("Assets/Easy Save 3/Open Easy Save 3 Window", false, 1000)]
public static void Init()
{
// Get existing open window or if none, make a new one:
ES3Window window = (ES3Window)EditorWindow.GetWindow(typeof(ES3Window));
if(window != null)
window.Show();
}
public static void InitAndShowHome()
{
// Get existing open window or if none, make a new one:
ES3Window window = (ES3Window)EditorWindow.GetWindow(typeof(ES3Window));
if (window != null)
{
window.Show();
window.SetCurrentWindow(typeof(HomeWindow));
}
}
[MenuItem("Tools/Easy Save 3/Auto Save", false, 100)]
public static void InitAndShowAutoSave()
{
// Get existing open window or if none, make a new one:
ES3Window window = (ES3Window)EditorWindow.GetWindow(typeof(ES3Window));
if (window != null)
{
window.Show();
window.SetCurrentWindow(typeof(AutoSaveWindow));
}
}
public static void InitAndShowReferences()
{
// Get existing open window or if none, make a new one:
ES3Window window = (ES3Window)EditorWindow.GetWindow(typeof(ES3Window));
if (window != null)
{
window.Show();
window.SetCurrentWindow(typeof(ReferencesWindow));
}
}
[MenuItem("Tools/Easy Save 3/Types", false, 100)]
public static void InitAndShowTypes()
{
// Get existing open window or if none, make a new one:
ES3Window window = (ES3Window)EditorWindow.GetWindow(typeof(ES3Window));
if (window != null)
{
window.Show();
window.SetCurrentWindow(typeof(TypesWindow));
}
}
public static void InitAndShowTypes(System.Type type)
{
// Get existing open window or if none, make a new one:
ES3Window window = (ES3Window)EditorWindow.GetWindow(typeof(ES3Window));
if (window != null)
{
window.Show();
var typesWindow = (TypesWindow)window.SetCurrentWindow(typeof(TypesWindow));
typesWindow.SelectType(type);
}
}
[MenuItem("Tools/Easy Save 3/Settings", false, 100)]
public static void InitAndShowSettings()
{
// Get existing open window or if none, make a new one:
ES3Window window = (ES3Window)EditorWindow.GetWindow(typeof(ES3Window));
if (window != null)
{
window.Show();
window.SetCurrentWindow(typeof(SettingsWindow));
}
}
[MenuItem("Tools/Easy Save 3/Tools", false, 100)]
public static void InitAndShowTools()
{
// Get existing open window or if none, make a new one:
ES3Window window = (ES3Window)EditorWindow.GetWindow(typeof(ES3Window));
if (window != null)
{
window.Show();
window.SetCurrentWindow(typeof(ToolsWindow));
}
}
public void InitSubWindows()
{
windows = new SubWindow[]{
new HomeWindow(this),
new SettingsWindow(this),
new ToolsWindow(this),
new TypesWindow(this),
new AutoSaveWindow(this)
//, new ReferencesWindow(this)
};
}
void OnLostFocus()
{
if(currentWindow != null)
currentWindow.OnLostFocus();
}
private void OnFocus()
{
if (currentWindow != null)
currentWindow.OnFocus();
}
void OnDestroy()
{
if(currentWindow != null)
currentWindow.OnDestroy();
}
void OnEnable()
{
if(windows == null)
InitSubWindows();
// Set the window name and icon.
var icon = AssetDatabase.LoadAssetAtPath<Texture2D>(ES3Settings.PathToEasySaveFolder()+"Editor/es3Logo16x16.png");
titleContent = new GUIContent("Easy Save", icon);
// Get the last opened window and open it.
if(currentWindow == null)
{
var currentWindowName = EditorPrefs.GetString("ES3Editor.Window.currentWindow", windows[0].name);
for(int i=0; i<windows.Length; i++)
{
if(windows[i].name == currentWindowName)
{
currentWindow = windows[i];
break;
}
}
}
}
private void OnHierarchyChange()
{
if (currentWindow != null)
currentWindow.OnHierarchyChange();
}
void OnGUI()
{
var style = EditorStyle.Get;
// Display the menu.
EditorGUILayout.BeginHorizontal();
for(int i=0; i<windows.Length; i++)
{
if(GUILayout.Button(windows[i].name, currentWindow == windows[i] ? style.menuButtonSelected : style.menuButton))
SetCurrentWindow(windows[i]);
}
EditorGUILayout.EndHorizontal();
if(currentWindow != null)
currentWindow.OnGUI();
}
void SetCurrentWindow(SubWindow window)
{
if (currentWindow != null)
currentWindow.OnLostFocus();
currentWindow = window;
currentWindow.OnFocus();
EditorPrefs.SetString("ES3Editor.Window.currentWindow", window.name);
}
SubWindow SetCurrentWindow(System.Type type)
{
currentWindow.OnLostFocus();
currentWindow = windows.First(w => w.GetType() == type);
EditorPrefs.SetString("ES3Editor.Window.currentWindow", currentWindow.name);
return currentWindow;
}
// Shows the Easy Save Home window if it's not been disabled.
// This method is called from the Postprocessor.
public static void OpenEditorWindowOnStart()
{
if(EditorPrefs.GetBool("Show ES3 Window on Start", true))
ES3Window.InitAndShowHome();
EditorPrefs.SetBool("Show ES3 Window on Start", false);
}
}
public abstract class SubWindow
{
public string name;
public EditorWindow parent;
public abstract void OnGUI();
public SubWindow(string name, EditorWindow parent)
{
this.name = name;
this.parent = parent;
}
public virtual void OnLostFocus()
{
}
public virtual void OnFocus()
{
}
public virtual void OnDestroy()
{
}
public virtual void OnHierarchyChange()
{
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 5705a3b4986f5dc45a72320e34b22a85
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,18 @@
{
"name": "EasySave3Editor",
"rootNamespace": "",
"references": [
"EasySave3"
],
"includePlatforms": [
"Editor"
],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": false
}

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 8b45730643e3af74da9313db9044adfa
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,23 @@
using UnityEditor;
using System.IO;
public class EnableES3AssemblyDefinitions : Editor
{
[MenuItem("Tools/Easy Save 3/Enable Assembly Definition Files", false, 150)]
public static void EnableAsmDef()
{
var pathToEasySaveFolder = ES3Settings.PathToEasySaveFolder();
File.Delete(pathToEasySaveFolder + "Editor/EasySave3.asmdef.disabled.meta");
File.Delete(pathToEasySaveFolder + "Editor/EasySave3Editor.asmdef.disabled.meta");
File.Move(pathToEasySaveFolder + "Editor/EasySave3Editor.asmdef.disabled", pathToEasySaveFolder + "Editor/EasySave3Editor.asmdef");
File.Move(pathToEasySaveFolder + "Editor/EasySave3.asmdef.disabled", pathToEasySaveFolder + "EasySave3.asmdef");
AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate);
EditorUtility.DisplayDialog("Assembly definition files installed", "Assembly definition files for Easy Save 3 installed.\n\nYou may need to go to 'Assets > Reimport' to apply the changes.", "Done");
}
[MenuItem("Tools/Easy Save 3/Enable Assembly Definition Files", true, 150)]
public static bool CanEnableAsmDef()
{
return !File.Exists(ES3Settings.PathToEasySaveFolder() + "EasySave3.asmdef");
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: d3eb22e7faecb4d4d8795c58ed4941df
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,70 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
namespace ES3Editor
{
public class HomeWindow : SubWindow
{
Vector2 scrollPos = Vector2.zero;
public HomeWindow(EditorWindow window) : base("Home", window){}
public override void OnGUI()
{
var style = EditorStyle.Get;
scrollPos = EditorGUILayout.BeginScrollView(scrollPos);
EditorGUILayout.BeginVertical(style.area);
GUILayout.Label("Welcome to Easy Save", style.heading);
EditorGUILayout.BeginVertical(style.area);
GUILayout.Label("New To Easy Save?", style.subheading);
EditorGUILayout.BeginVertical(style.area);
ES3EditorUtility.DisplayLink("• See our Getting Started guide", "http://docs.moodkie.com/easy-save-3/getting-started/");
EditorGUILayout.EndVertical();
GUILayout.Label("Support", style.subheading);
EditorGUILayout.BeginVertical(style.area);
ES3EditorUtility.DisplayLink("• Contact us directly", "http://www.moodkie.com/contact/");
ES3EditorUtility.DisplayLink("• Ask a question in our Easy Save 3 forums", "http://moodkie.com/forum/viewforum.php?f=12");
ES3EditorUtility.DisplayLink("• Ask a question in the Unity Forum thread","https://forum.unity3d.com/threads/easy-save-the-complete-save-load-asset-for-unity.91040/");
EditorGUILayout.EndVertical();
GUILayout.Label("Documentation and Guides", style.subheading);
EditorGUILayout.BeginVertical(style.area);
ES3EditorUtility.DisplayLink("• Documentation", "http://docs.moodkie.com/product/easy-save-3/");
ES3EditorUtility.DisplayLink("• Guides", "http://docs.moodkie.com/product/easy-save-3/es3-guides/");
ES3EditorUtility.DisplayLink("• API Scripting Reference", "http://docs.moodkie.com/product/easy-save-3/es3-api/");
ES3EditorUtility.DisplayLink("• Supported Types", "http://docs.moodkie.com/easy-save-3/es3-supported-types/");
EditorGUILayout.EndVertical();
GUILayout.Label("PlayMaker Documentation", style.subheading);
EditorGUILayout.BeginVertical(style.area);
ES3EditorUtility.DisplayLink("• Actions", "http://docs.moodkie.com/product/easy-save-3/es3-playmaker/es3-playmaker-actions/");
ES3EditorUtility.DisplayLink("• Actions Overview", "http://docs.moodkie.com/easy-save-3/es3-playmaker/playmaker-actions-overview/");
EditorGUILayout.EndVertical();
EditorGUILayout.EndVertical();
EditorGUILayout.EndVertical();
EditorGUILayout.EndScrollView();
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: b13f68af28a0b0a41bddf87cc04eda90
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,21 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using ES3Internal;
namespace ES3Editor
{
public class ReferencesWindow : SubWindow
{
public ReferencesWindow(EditorWindow window) : base("References", window){}
public override void OnGUI()
{
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 11877eab051d44a4284b2bba24a5c080
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,182 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using ES3Internal;
namespace ES3Editor
{
public class SettingsWindow : SubWindow
{
public ES3Defaults editorSettings = null;
public ES3SerializableSettings settings = null;
public SerializedObject so = null;
public SerializedProperty referenceFoldersProperty = null;
private Vector2 scrollPos = Vector2.zero;
public SettingsWindow(EditorWindow window) : base("Settings", window){}
public void OnEnable()
{
}
public override void OnGUI()
{
if(settings == null || editorSettings == null)
Init();
var style = EditorStyle.Get;
var labelWidth = EditorGUIUtility.labelWidth;
EditorGUI.BeginChangeCheck();
using (var scrollView = new EditorGUILayout.ScrollViewScope(scrollPos, style.area))
{
scrollPos = scrollView.scrollPosition;
EditorGUIUtility.labelWidth = 160;
GUILayout.Label("Runtime Settings", style.heading);
using (new EditorGUILayout.VerticalScope(style.area))
{
ES3SettingsEditor.Draw(settings);
}
GUILayout.Label("Debug Settings", style.heading);
using (new EditorGUILayout.VerticalScope(style.area))
{
EditorGUIUtility.labelWidth = 100;
using (new EditorGUILayout.HorizontalScope())
{
EditorGUILayout.PrefixLabel("Log Info");
editorSettings.logDebugInfo = EditorGUILayout.Toggle(editorSettings.logDebugInfo);
}
using (new EditorGUILayout.HorizontalScope())
{
EditorGUILayout.PrefixLabel("Log Warnings");
editorSettings.logWarnings = EditorGUILayout.Toggle(editorSettings.logWarnings);
}
using (new EditorGUILayout.HorizontalScope())
{
EditorGUILayout.PrefixLabel("Log Errors");
editorSettings.logErrors = EditorGUILayout.Toggle(editorSettings.logErrors);
}
EditorGUILayout.Space();
}
GUILayout.Label("Editor Settings", style.heading);
using (new EditorGUILayout.VerticalScope(style.area))
{
EditorGUIUtility.labelWidth = 170;
using (new EditorGUILayout.HorizontalScope())
{
EditorGUILayout.PrefixLabel("Auto Update References");
editorSettings.autoUpdateReferences = EditorGUILayout.Toggle(editorSettings.autoUpdateReferences);
}
if (editorSettings.autoUpdateReferences)
{
using (new EditorGUILayout.HorizontalScope())
{
var content = new GUIContent("-- When changes are made", "Should Easy Save update the reference manager when objects in your scene changes?");
editorSettings.updateReferencesWhenSceneChanges = EditorGUILayout.Toggle(content, editorSettings.updateReferencesWhenSceneChanges);
}
using (new EditorGUILayout.HorizontalScope())
{
var content = new GUIContent("-- When scene is saved", "Should Easy Save update the reference manager when objects in your scene is saved?");
editorSettings.updateReferencesWhenSceneIsSaved = EditorGUILayout.Toggle(content, editorSettings.updateReferencesWhenSceneIsSaved);
}
using (new EditorGUILayout.HorizontalScope())
{
var content = new GUIContent("-- When scene is opened", "Should Easy Save update the reference manager you open a scene in the Editor?");
editorSettings.updateReferencesWhenSceneIsOpened = EditorGUILayout.Toggle(content, editorSettings.updateReferencesWhenSceneIsOpened);
}
EditorGUILayout.Space();
}
using (new EditorGUILayout.HorizontalScope())
{
so.Update();
EditorGUILayout.PropertyField(referenceFoldersProperty, true);
so.ApplyModifiedProperties();
}
EditorGUILayout.Space();
/*using (new EditorGUILayout.HorizontalScope())
{
var content = new GUIContent("Reference depth", "How deep should Easy Save look when gathering references from an object? Higher means deeper.");
EditorGUILayout.PrefixLabel(content);
editorSettings.collectDependenciesDepth = EditorGUILayout.IntField(editorSettings.collectDependenciesDepth);
}*/
using (new EditorGUILayout.HorizontalScope())
{
var content = new GUIContent("Reference timeout (seconds)", "How many seconds should Easy Save taking collecting references for an object before timing out?");
EditorGUILayout.PrefixLabel(content);
editorSettings.collectDependenciesTimeout = EditorGUILayout.IntField(editorSettings.collectDependenciesTimeout);
}
using (new EditorGUILayout.HorizontalScope())
{
EditorGUILayout.PrefixLabel("Use Global References");
var symbols = PlayerSettings.GetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup);
bool useGlobalReferences = !symbols.Contains("ES3GLOBAL_DISABLED");
if(EditorGUILayout.Toggle(useGlobalReferences) != useGlobalReferences)
{
// Remove the existing symbol even if we're disabling global references, just incase it's already in there.
symbols = symbols.Replace("ES3GLOBAL_DISABLED;", ""); // With semicolon
symbols = symbols.Replace("ES3GLOBAL_DISABLED", ""); // Without semicolon
// Add the symbol if useGlobalReferences is currently true, meaning that we want to disable it.
if (useGlobalReferences)
symbols = "ES3GLOBAL_DISABLED;" + symbols;
PlayerSettings.SetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup, symbols);
if(useGlobalReferences)
EditorUtility.DisplayDialog("Global references disabled for build platform", "This will only disable Global References for this build platform. To disable it for other build platforms, open that platform in the Build Settings and uncheck this box again.", "Ok");
}
}
using (new EditorGUILayout.HorizontalScope())
{
var content = new GUIContent("Add All Prefabs to Manager", "Should all prefabs with ES3Prefab Components be added to the manager?");
EditorGUILayout.PrefixLabel(content);
editorSettings.addAllPrefabsToManager = EditorGUILayout.Toggle(editorSettings.addAllPrefabsToManager);
}
EditorGUILayout.Space();
}
}
if (EditorGUI.EndChangeCheck())
EditorUtility.SetDirty(editorSettings);
EditorGUIUtility.labelWidth = labelWidth; // Set the label width back to default
}
public void Init()
{
editorSettings = ES3Settings.defaultSettingsScriptableObject;
settings = editorSettings.settings;
so = new SerializedObject(editorSettings);
referenceFoldersProperty = so.FindProperty("referenceFolders");
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 4abde3eeeebf7de42ab0642aadc9c5f2
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,155 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.IO;
namespace ES3Editor
{
public class ToolsWindow : SubWindow
{
public ToolsWindow(EditorWindow window) : base("Tools", window){}
public override void OnGUI()
{
var style = EditorStyle.Get;
EditorGUILayout.BeginHorizontal(style.area);
if (GUILayout.Button("Open Persistent Data Path"))
OpenPersistentDataPath();
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal(style.area);
if (GUILayout.Button("Clear Persistent Data Path"))
ClearPersistentDataPath();
if (GUILayout.Button("Clear PlayerPrefs"))
ClearPlayerPrefs();
EditorGUILayout.EndHorizontal();
}
[MenuItem("Tools/Easy Save 3/Open Persistent Data Path", false, 200)]
private static void OpenPersistentDataPath()
{
EditorUtility.RevealInFinder(Application.persistentDataPath);
}
[MenuItem("Tools/Easy Save 3/Clear Persistent Data Path", false, 200)]
private static void ClearPersistentDataPath()
{
if (EditorUtility.DisplayDialog("Clear Persistent Data Path", "Are you sure you wish to clear the persistent data path?\n This action cannot be reversed.", "Clear", "Cancel"))
{
System.IO.DirectoryInfo di = new DirectoryInfo(Application.persistentDataPath);
foreach (FileInfo file in di.GetFiles())
file.Delete();
foreach (DirectoryInfo dir in di.GetDirectories())
dir.Delete(true);
}
}
[MenuItem("Tools/Easy Save 3/Clear PlayerPrefs", false, 200)]
private static void ClearPlayerPrefs()
{
if (EditorUtility.DisplayDialog("Clear PlayerPrefs", "Are you sure you wish to clear PlayerPrefs?\nThis action cannot be reversed.", "Clear", "Cancel"))
PlayerPrefs.DeleteAll();
}
}
/*public static class OSFileBrowser
{
public static bool IsInMacOS
{
get
{
return UnityEngine.SystemInfo.operatingSystem.IndexOf("Mac OS") != -1;
}
}
public static bool IsInWinOS
{
get
{
return UnityEngine.SystemInfo.operatingSystem.IndexOf("Windows") != -1;
}
}
public static void OpenInMac(string path)
{
bool openInsidesOfFolder = false;
// try mac
string macPath = path.Replace("\\", "/"); // mac finder doesn't like backward slashes
if ( System.IO.Directory.Exists(macPath) ) // if path requested is a folder, automatically open insides of that folder
{
openInsidesOfFolder = true;
}
if ( !macPath.StartsWith("\"") )
{
macPath = "\"" + macPath;
}
if ( !macPath.EndsWith("\"") )
{
macPath = macPath + "\"";
}
string arguments = (openInsidesOfFolder ? "" : "-R ") + macPath;
try
{
System.Diagnostics.Process.Start("open", arguments);
}
catch ( System.ComponentModel.Win32Exception e )
{
// tried to open mac finder in windows
// just silently skip error
// we currently have no platform define for the current OS we are in, so we resort to this
e.HelpLink = ""; // do anything with this variable to silence warning about not using it
}
}
public static void OpenInWin(string path)
{
bool openInsidesOfFolder = false;
// try windows
string winPath = path.Replace("/", "\\"); // windows explorer doesn't like forward slashes
if ( System.IO.Directory.Exists(winPath) ) // if path requested is a folder, automatically open insides of that folder
openInsidesOfFolder = true;
try
{
System.Diagnostics.Process.Start("explorer.exe", (openInsidesOfFolder ? "/root," : "/select,") + "\"" + winPath + "\"");
}
catch ( System.ComponentModel.Win32Exception e )
{
e.HelpLink = "";
}
}
public static void Open(string path)
{
if ( IsInWinOS )
{
OpenInWin(path);
}
else if ( IsInMacOS )
{
OpenInMac(path);
}
else // couldn't determine OS
{
OpenInWin(path);
OpenInMac(path);
}
}
}*/
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 9b38aa962617c63499652b47dda9d5c0
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,726 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System;
using System.Reflection;
using System.Linq;
using ES3Types;
using System.IO;
using ES3Internal;
using System.Text.RegularExpressions;
namespace ES3Editor
{
public class TypesWindow : SubWindow
{
TypeListItem[] types = null;
const int recentTypeCount = 5;
List<int> recentTypes = null;
Vector2 typeListScrollPos = Vector2.zero;
Vector2 typePaneScrollPos = Vector2.zero;
int leftPaneWidth = 300;
string searchFieldValue = "";
int selectedType = -1;
private ES3Reflection.ES3ReflectedMember[] fields = new ES3Reflection.ES3ReflectedMember[0];
private bool[] fieldSelected = new bool[0];
private Texture2D checkmark;
//private Texture2D checkmarkSmall;
private GUIStyle searchBarStyle;
private GUIStyle searchBarCancelButtonStyle;
private GUIStyle leftPaneStyle;
private GUIStyle typeButtonStyle;
private GUIStyle selectedTypeButtonStyle;
private GUIStyle selectAllNoneButtonStyle;
private string valueTemplateFile;
private string classTemplateFile;
private string componentTemplateFile;
private string scriptableObjectTemplateFile;
private bool unsavedChanges = false;
public TypesWindow(EditorWindow window) : base("Types", window){}
public override void OnGUI()
{
if(types == null)
Init();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.BeginVertical(leftPaneStyle);
SearchBar();
TypeList();
EditorGUILayout.EndVertical();
EditorGUILayout.BeginVertical();
TypePane();
EditorGUILayout.EndVertical();
EditorGUILayout.EndHorizontal();
}
private void SearchBar()
{
var style = EditorStyle.Get;
GUILayout.Label("Enter a type name in the field below\n* Type names are case-sensitive *", style.subheading2);
EditorGUILayout.BeginHorizontal();
// Set control name so we can force a Focus reset for it.
string currentSearchFieldValue = EditorGUILayout.TextField(searchFieldValue, searchBarStyle);
if(searchFieldValue != currentSearchFieldValue)
{
searchFieldValue = currentSearchFieldValue;
PerformSearch(currentSearchFieldValue);
}
GUI.SetNextControlName("Clear");
if(GUILayout.Button("x", searchBarCancelButtonStyle))
{
searchFieldValue = "";
GUI.FocusControl("Clear");
PerformSearch("");
}
EditorGUILayout.EndHorizontal();
}
private void RecentTypeList()
{
if(!string.IsNullOrEmpty(searchFieldValue) || recentTypes.Count == 0)
return;
for(int i=recentTypes.Count-1; i>-1; i--)
TypeButton(recentTypes[i]);
EditorGUILayout.TextArea("",GUI.skin.horizontalSlider);
}
private void TypeList()
{
if(!string.IsNullOrEmpty(searchFieldValue))
GUILayout.Label("Search Results", EditorStyles.boldLabel);
typeListScrollPos = EditorGUILayout.BeginScrollView(typeListScrollPos);
RecentTypeList();
if(!string.IsNullOrEmpty(searchFieldValue))
for(int i = 0; i < types.Length; i++)
TypeButton(i);
EditorGUILayout.EndScrollView();
}
private void TypePane()
{
if(selectedType < 0)
return;
var style = EditorStyle.Get;
var typeListItem = types[selectedType];
var type = typeListItem.type;
typePaneScrollPos = EditorGUILayout.BeginScrollView(typePaneScrollPos, style.area);
GUILayout.Label(typeListItem.name, style.subheading);
GUILayout.Label(typeListItem.namespaceName);
EditorGUILayout.BeginVertical(style.area);
bool hasParameterlessConstructor = ES3Reflection.HasParameterlessConstructor(type);
bool isComponent = ES3Reflection.IsAssignableFrom(typeof(Component), type);
string path = GetOutputPath(types[selectedType].type);
// An ES3Type file already exists.
if(File.Exists(path))
{
if(hasParameterlessConstructor || isComponent)
{
EditorGUILayout.BeginHorizontal();
if(GUILayout.Button("Reset to Default"))
{
SelectNone(true, true);
AssetDatabase.MoveAssetToTrash("Assets" + path.Remove(0, Application.dataPath.Length));
SelectType(selectedType);
}
if(GUILayout.Button("Edit ES3Type Script"))
AssetDatabase.OpenAsset(AssetDatabase.LoadMainAssetAtPath("Assets" + path.Remove(0, Application.dataPath.Length)));
EditorGUILayout.EndHorizontal();
}
else
{
EditorGUILayout.HelpBox("This type has no public parameterless constructors.\n\nTo support this type you will need to modify the ES3Type script to use a specific constructor instead of the parameterless constructor.", MessageType.Info);
if(GUILayout.Button("Click here to edit the ES3Type script"))
AssetDatabase.OpenAsset(AssetDatabase.LoadMainAssetAtPath("Assets" + path.Remove(0, Application.dataPath.Length)));
if (GUILayout.Button("Reset to Default"))
{
SelectAll(true, true);
File.Delete(path);
AssetDatabase.Refresh();
}
}
}
// No ES3Type file and no fields.
else if(fields.Length == 0)
{
if(!hasParameterlessConstructor && !isComponent)
EditorGUILayout.HelpBox("This type has no public parameterless constructors.\n\nTo support this type you will need to create an ES3Type script and modify it to use a specific constructor instead of the parameterless constructor.", MessageType.Info);
if(GUILayout.Button("Create ES3Type Script"))
Generate();
}
// No ES3Type file, but fields are selectable.
else
{
if(!hasParameterlessConstructor && !isComponent)
{
EditorGUILayout.HelpBox("This type has no public parameterless constructors.\n\nTo support this type you will need to select the fields you wish to serialize below, and then modify the generated ES3Type script to use a specific constructor instead of the parameterless constructor.", MessageType.Info);
if(GUILayout.Button("Select all fields and generate ES3Type script"))
{
SelectAll(true, false);
Generate();
}
}
else
{
if(GUILayout.Button("Create ES3Type Script"))
Generate();
}
}
EditorGUILayout.EndVertical();
PropertyPane();
EditorGUILayout.EndScrollView();
}
private void PropertyPane()
{
var style = EditorStyle.Get;
EditorGUILayout.BeginVertical(style.area);
GUILayout.Label("Fields", EditorStyles.boldLabel);
DisplayFieldsOrProperties(true, false);
EditorGUILayout.Space();
GUILayout.Label("Properties", EditorStyles.boldLabel);
DisplayFieldsOrProperties(false, true);
EditorGUILayout.EndVertical();
}
private void DisplayFieldsOrProperties(bool showFields, bool showProperties)
{
// Get field and property counts.
int fieldCount = 0;
int propertyCount = 0;
for(int i=0; i<fields.Length; i++)
{
if(fields[i].isProperty && showProperties)
propertyCount++;
else if((!fields[i].isProperty) && showFields)
fieldCount++;
}
// If there is nothing to display, show message.
if(showFields && showProperties && fieldCount == 0 && propertyCount == 0)
GUILayout.Label("This type has no serializable fields or properties.");
else if(showFields && fieldCount == 0)
GUILayout.Label("This type has no serializable fields.");
else if(showProperties && propertyCount == 0)
GUILayout.Label("This type has no serializable properties.");
// Display Select All/Select None buttons only if there are fields to display.
if(fieldCount > 0 || propertyCount > 0)
{
EditorGUILayout.BeginHorizontal();
if(GUILayout.Button("Select All", selectAllNoneButtonStyle))
{
SelectAll(showFields, showProperties);
Generate();
}
if(GUILayout.Button("Select None", selectAllNoneButtonStyle))
{
SelectNone(showFields, showProperties);
Generate();
}
EditorGUILayout.EndHorizontal();
}
for(int i=0; i<fields.Length; i++)
{
var field = fields[i];
if((field.isProperty && !showProperties) || ((!field.isProperty) && !showFields))
continue;
EditorGUILayout.BeginHorizontal();
var content = new GUIContent(field.Name);
if(typeof(UnityEngine.Object).IsAssignableFrom(field.MemberType))
content.tooltip = field.MemberType.ToString() + "\nSaved by reference";
else
content.tooltip = field.MemberType.ToString() + "\nSaved by value";
bool selected = EditorGUILayout.ToggleLeft(content, fieldSelected[i]);
if(selected != fieldSelected[i])
{
fieldSelected[i] = selected;
unsavedChanges = true;
}
EditorGUILayout.EndHorizontal();
}
}
// Selects all fields, properties or both.
private void SelectAll(bool selectFields, bool selectProperties)
{
for(int i=0; i<fieldSelected.Length; i++)
if((fields[i].isProperty && selectProperties) || (!fields[i].isProperty) && selectFields)
fieldSelected[i] = true;
}
// Selects all fields, properties or both.
private void SelectNone(bool selectFields, bool selectProperties)
{
for(int i=0; i<fieldSelected.Length; i++)
if((fields[i].isProperty && selectProperties) || (!fields[i].isProperty) && selectFields)
fieldSelected[i] = false;
}
public override void OnLostFocus()
{
if(unsavedChanges)
Generate();
}
private void TypeButton(int i)
{
var type = types[i];
if(!types[i].showInList)
return;
if(type.hasExplicitES3Type)
EditorGUILayout.BeginHorizontal();
var thisTypeButtonStyle = (i == selectedType) ? selectedTypeButtonStyle : typeButtonStyle;
if(GUILayout.Button(new GUIContent(type.name, type.namespaceName), thisTypeButtonStyle))
SelectType(i);
// Set the cursor.
var buttonRect = GUILayoutUtility.GetLastRect();
EditorGUIUtility.AddCursorRect(buttonRect, MouseCursor.Link);
if(type.hasExplicitES3Type)
{
GUILayout.Box(new GUIContent(checkmark, "Type is explicitly supported"), EditorStyles.largeLabel);
EditorGUILayout.EndHorizontal();
}
}
private void PerformSearch(string query)
{
var lowerCaseQuery = query.ToLowerInvariant();
var emptyQuery = string.IsNullOrEmpty(query);
for(int i=0; i<types.Length; i++)
types[i].showInList = (emptyQuery || types[i].lowercaseName.Contains(lowerCaseQuery));
}
public void SelectType(Type type)
{
Init();
for (int i = 0; i < types.Length; i++)
if (types[i].type == type)
SelectType(i);
}
private void SelectType(int typeIndex)
{
selectedType = typeIndex;
if(selectedType == -1)
{
SaveType("TypesWindowSelectedType", -1);
return;
}
SaveType("TypesWindowSelectedType", selectedType);
if(!recentTypes.Contains(typeIndex))
{
// If our recent type queue is full, remove an item before adding another.
if(recentTypes.Count == recentTypeCount)
recentTypes.RemoveAt(0);
recentTypes.Add(typeIndex);
for(int j=0; j<recentTypes.Count; j++)
SaveType("TypesWindowRecentType"+j, recentTypes[j]);
}
var type = types[selectedType].type;
fields = ES3Reflection.GetSerializableMembers(type, false);
fieldSelected = new bool[fields.Length];
var es3Type = ES3TypeMgr.GetES3Type(type);
// If there's no ES3Type for this, only select fields which are supported by reflection.
if(es3Type == null)
{
var safeFields = ES3Reflection.GetSerializableMembers(type, true);
for(int i=0; i<fields.Length; i++)
fieldSelected[i] = safeFields.Any(item => item.Name == fields[i].Name);
return;
}
// Get fields and whether they're selected.
var selectedFields = new List<string>();
var propertyAttributes = es3Type.GetType().GetCustomAttributes(typeof(ES3PropertiesAttribute), false);
if(propertyAttributes.Length > 0)
selectedFields.AddRange(((ES3PropertiesAttribute)propertyAttributes[0]).members);
fieldSelected = new bool[fields.Length];
for(int i=0; i<fields.Length; i++)
fieldSelected[i] = selectedFields.Contains(fields[i].Name);
}
private void SaveType(string key, int typeIndex)
{
if(typeIndex == -1)
return;
SaveType(key, types[typeIndex].type);
}
private void SaveType(string key, Type type)
{
EditorPrefs.SetString(key, type.AssemblyQualifiedName);
}
private int LoadTypeIndex(string key)
{
string selectedTypeName = EditorPrefs.GetString(key, "");
if(selectedTypeName != "")
{
var type = ES3Reflection.GetType(selectedTypeName);
if(type != null)
{
int typeIndex = GetTypeIndex(type);
if(typeIndex != -1)
return typeIndex;
}
}
return -1;
}
private int GetTypeIndex(Type type)
{
for(int i=0; i<types.Length; i++)
if(types[i].type == type)
return i;
return -1;
}
private void Init()
{
componentTemplateFile = "ES3ComponentTypeTemplate.txt";
classTemplateFile = "ES3ClassTypeTemplate.txt";
valueTemplateFile = "ES3ValueTypeTemplate.txt";
scriptableObjectTemplateFile = "ES3ScriptableObjectTypeTemplate.txt";
// Init Type List
var tempTypes = new List<TypeListItem> ();
var assemblies = AppDomain.CurrentDomain.GetAssemblies().Where(assembly => !assembly.FullName.Contains("Editor") && assembly.FullName != "ES3" && !assembly.FullName.Contains("ES3")).OrderBy(assembly => assembly.GetName().Name).ToArray();
foreach (var assembly in assemblies)
{
var assemblyTypes = assembly.GetTypes();
for(int i = 0; i < assemblyTypes.Length; i++)
{
var type = assemblyTypes [i];
if(type.IsGenericType || type.IsEnum || type.IsNotPublic || type.IsAbstract || type.IsInterface)
continue;
var typeName = type.Name;
if(typeName [0] == '$' || typeName [0] == '_' || typeName [0] == '<')
continue;
var typeNamespace = type.Namespace;
var namespaceName = typeNamespace == null ? "" : typeNamespace.ToString();
tempTypes.Add(new TypeListItem (type.Name, namespaceName, type, true, HasExplicitES3Type(type)));
}
}
types = tempTypes.OrderBy(type => type.name).ToArray();
// Load types and recent types.
if (recentTypes == null)
{
recentTypes = new List<int>();
for (int i = 0; i < recentTypeCount; i++)
{
int typeIndex = LoadTypeIndex("TypesWindowRecentType" + i);
if (typeIndex != -1)
recentTypes.Add(typeIndex);
}
SelectType(LoadTypeIndex("TypesWindowSelectedType"));
}
PerformSearch(searchFieldValue);
// Init Assets.
string es3FolderPath = ES3Settings.PathToEasySaveFolder();
checkmark = AssetDatabase.LoadAssetAtPath<Texture2D>(es3FolderPath + "Editor/checkmark.png");
//checkmarkSmall = AssetDatabase.LoadAssetAtPath<Texture2D>(es3FolderPath + "Editor/checkmarkSmall.png");
// Init Styles.
searchBarCancelButtonStyle = new GUIStyle(EditorStyles.miniButton);
var cancelButtonSize = EditorStyles.miniTextField.CalcHeight(new GUIContent(""), 20);
searchBarCancelButtonStyle.fixedWidth = cancelButtonSize;
searchBarCancelButtonStyle.fixedHeight = cancelButtonSize;
searchBarCancelButtonStyle.fontSize = 8;
searchBarCancelButtonStyle.padding = new RectOffset();
searchBarStyle = new GUIStyle(EditorStyles.toolbarTextField);
searchBarStyle.stretchWidth = true;
typeButtonStyle = new GUIStyle(EditorStyles.largeLabel);
typeButtonStyle.alignment = TextAnchor.MiddleLeft;
typeButtonStyle.stretchWidth = false;
selectedTypeButtonStyle = new GUIStyle(typeButtonStyle);
selectedTypeButtonStyle.fontStyle = FontStyle.Bold;
leftPaneStyle = new GUIStyle();
leftPaneStyle.fixedWidth = leftPaneWidth;
leftPaneStyle.clipping = TextClipping.Clip;
leftPaneStyle.padding = new RectOffset(10, 10, 10, 10);
selectAllNoneButtonStyle = new GUIStyle(EditorStyles.miniButton);
selectAllNoneButtonStyle.stretchWidth = false;
selectAllNoneButtonStyle.margin = new RectOffset(0,0,0,10);
}
private void Generate()
{
var type = types[selectedType].type;
if(type == null)
{
EditorUtility.DisplayDialog("Type not selected", "Type not selected. Please ensure you select a type", "Ok");
return;
}
unsavedChanges = false;
// Get the serializable fields of this class.
//var fields = ES3Reflection.GetSerializableES3Fields(type);
// The string that we suffix to the class name. i.e. UnityEngine_UnityEngine_Transform.
string es3TypeSuffix = type.Name;
// The string for the full C#-safe type name. This name must be suitable for going inside typeof().
string fullType = GetFullTypeName(type);
// The list of WriteProperty calls to write the properties of this type.
string writes = GenerateWrites();
// The list of case statements and Read calls to read the properties of this type.
string reads = GenerateReads();
// A comma-seperated string of fields we've supported in this type.
string propertyNames = "";
bool first = true;
for(int i=0; i<fields.Length; i++)
{
if(!fieldSelected[i])
continue;
if(first)
first = false;
else
propertyNames += ", ";
propertyNames += "\"" + fields[i].Name + "\"";
}
var easySaveEditorPath = ES3Settings.PathToEasySaveFolder()+"Editor/";
// Insert the relevant strings into the template.
string template;
if(typeof(Component).IsAssignableFrom(type))
template = File.ReadAllText(easySaveEditorPath + componentTemplateFile);
else if(ES3Reflection.IsValueType(type))
template = File.ReadAllText(easySaveEditorPath + valueTemplateFile);
else if(typeof(ScriptableObject).IsAssignableFrom(type))
template = File.ReadAllText(easySaveEditorPath + scriptableObjectTemplateFile);
else
template = File.ReadAllText(easySaveEditorPath + classTemplateFile);
template = template.Replace("[es3TypeSuffix]", es3TypeSuffix);
template = template.Replace("[writes]", writes);
template = template.Replace("[reads]", reads);
template = template.Replace("[propertyNames]", propertyNames);
template = template.Replace("[fullType]", fullType); // Do this last as we use the [fullType] tag in reads.
// Create the output file.
string outputFilePath = GetOutputPath(type);
var fileInfo = new FileInfo(outputFilePath);
fileInfo.Directory.Create();
File.WriteAllText(outputFilePath, template);
AssetDatabase.Refresh();
}
private string GenerateWrites()
{
var type = types[selectedType].type;
bool isComponent = typeof(Component).IsAssignableFrom(type);
string writes = "";
for(int i=0; i<fields.Length; i++)
{
var field = fields[i];
var selected = fieldSelected[i];
var es3Type = ES3TypeMgr.GetES3Type(field.MemberType);
if(!selected || isComponent && (field.Name == ES3Reflection.componentTagFieldName || field.Name == ES3Reflection.componentNameFieldName))
continue;
string writeByRef = ES3Reflection.IsAssignableFrom(typeof(UnityEngine.Object), field.MemberType) ? "ByRef" : "";
string es3TypeParam = HasExplicitES3Type(es3Type) && writeByRef == "" && !field.MemberType.IsEnum ? ", " + es3Type.GetType().Name + ".Instance" : (writeByRef == "" ? ", ES3Internal.ES3TypeMgr.GetOrCreateES3Type(typeof(" + GetFullTypeName(field.MemberType) + "))" : "");
// If this is static, access the field through the class name rather than through an instance.
string instance = (field.IsStatic) ? GetFullTypeName(type) : "instance";
if(!field.IsPublic)
{
string memberType = field.isProperty ? "Property" : "Field";
writes += String.Format("\r\n\t\t\twriter.WritePrivate{2}{1}(\"{0}\", instance);", field.Name, writeByRef, memberType);
}
else
writes += String.Format("\r\n\t\t\twriter.WriteProperty{1}(\"{0}\", {3}.{0}{2});", field.Name, writeByRef, es3TypeParam, instance);
}
return writes;
}
private string GenerateReads()
{
var type = types[selectedType].type;
bool isComponent = typeof(Component).IsAssignableFrom(type);
string reads = "";
for(int i=0; i<fields.Length; i++)
{
var field = fields[i];
var selected = fieldSelected[i];
if(!selected || isComponent && (field.Name == "tag" || field.Name == "name"))
continue;
string fieldTypeName = GetFullTypeName(field.MemberType);
string es3TypeParam = HasExplicitES3Type(field.MemberType) ? ES3TypeMgr.GetES3Type(field.MemberType).GetType().Name+".Instance" : "";
// If this is static, access the field through the class name rather than through an instance.
string instance = (field.IsStatic) ? GetFullTypeName(type) : "instance";
// If we're writing a private field or property, we need to write it using a different method.
if(!field.IsPublic)
{
es3TypeParam = ", " + es3TypeParam;
if(field.isProperty)
reads += String.Format("\r\n\t\t\t\t\tcase \"{0}\":\r\n\t\t\t\t\tinstance = ([fullType])reader.SetPrivateProperty(\"{0}\", reader.Read<{1}>(), instance);\r\n\t\t\t\t\tbreak;", field.Name, fieldTypeName);
else
reads += String.Format("\r\n\t\t\t\t\tcase \"{0}\":\r\n\t\t\t\t\tinstance = ([fullType])reader.SetPrivateField(\"{0}\", reader.Read<{1}>(), instance);\r\n\t\t\t\t\tbreak;", field.Name, fieldTypeName);
}
else
reads += String.Format("\r\n\t\t\t\t\tcase \"{0}\":\r\n\t\t\t\t\t\t{3}.{0} = reader.Read<{1}>({2});\r\n\t\t\t\t\t\tbreak;", field.Name, fieldTypeName, es3TypeParam, instance);
}
return reads;
}
private string GetOutputPath(Type type)
{
return Application.dataPath + "/Easy Save 3/Types/ES3UserType_"+type.Name+".cs";
}
/* Gets the full Type name, replacing any syntax (such as '+') with a dot to make it a valid type name */
private static string GetFullTypeName(Type type)
{
string typeName = type.ToString();
typeName = typeName.Replace('+','.');
// If it's a generic type, replace syntax with angled brackets.
int genericArgumentCount = type.GetGenericArguments().Length;
if(genericArgumentCount > 0)
{
return string.Format("{0}<{1}>", type.ToString().Split('`')[0], string.Join(", ", type.GetGenericArguments().Select(x => GetFullTypeName(x)).ToArray()));
}
return typeName;
}
/* Whether this type has an explicit ES3Type. For example, ES3ArrayType would return false, but ES3Vector3ArrayType would return true */
private static bool HasExplicitES3Type(Type type)
{
var es3Type = ES3TypeMgr.GetES3Type(type);
if(es3Type == null)
return false;
// If this ES3Type has a static Instance property, return true.
if(es3Type.GetType().GetField("Instance", BindingFlags.Public | BindingFlags.Static) != null)
return true;
return false;
}
private static bool HasExplicitES3Type(ES3Type es3Type)
{
if(es3Type == null)
return false;
// If this ES3Type has a static Instance property, return true.
if(es3Type.GetType().GetField("Instance", BindingFlags.Public | BindingFlags.Static) != null)
return true;
return false;
}
public class TypeListItem
{
public string name;
public string lowercaseName;
public string namespaceName;
public Type type;
public bool showInList;
public bool hasExplicitES3Type;
public TypeListItem(string name, string namespaceName, Type type, bool showInList, bool hasExplicitES3Type)
{
this.name = name;
this.lowercaseName = name.ToLowerInvariant();
this.namespaceName = namespaceName;
this.type = type;
this.showInList = showInList;
this.hasExplicitES3Type = hasExplicitES3Type;
}
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 291bb86b9f34bc448b86f0708e964326
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 855299ead809caf4abb5c15078e35079
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 8ab77881cfd0ca544a12c4ea66458e53
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: c8e4a7434fe6c834785678a1bac26abf
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: ed89ec3791d0af84da42266491e37b30
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,60 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!114 &11400000
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 0}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 046a2c1130f1d594dbf05ad57a8b0265, type: 3}
m_Name: ES3Defaults
m_EditorClassIdentifier:
settings:
_location: 0
path: SaveFile.es3
encryptionType: 0
compressionType: 0
encryptionPassword: password
directory: 0
format: 0
prettyPrint: 1
bufferSize: 2048
saveChildren: 1
postprocessRawCachedData: 0
typeChecking: 1
safeReflection: 1
memberReferenceMode: 0
referenceMode: 2
serializationDepthLimit: 64
assemblyNames:
- AimingRig
- Assembly-CSharp
- Assembly-CSharp-firstpass
- Cinemachine
- Convention.Plugin
- Convention.Runtime
- Convention.Windows
- CW.Common
- Dreamteck.Splines
- Dreamteck.Utilities
- EasySave3
- IngameDebugConsole.Runtime
- LeanCommon
- LeanPool
- WorkflowAgent
showAdvancedSettings: 0
addMgrToSceneAutomatically: 0
autoUpdateReferences: 1
addAllPrefabsToManager: 1
collectDependenciesDepth: 4
collectDependenciesTimeout: 10
updateReferencesWhenSceneChanges: 1
updateReferencesWhenSceneIsSaved: 1
updateReferencesWhenSceneIsOpened: 1
referenceFolders: []
logDebugInfo: 0
logWarnings: 1
logErrors: 1

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: cd233b5bd72925e4e9e62227cc374cb4
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 11400000
userData:
assetBundleName:
assetBundleVariant:

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 32c8e912c74222a439c018f24dd7f268
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 0
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 15119d527b6fb7a44834fa8e413c68d1
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 8f71580da063e964fb401ef50309f6d8
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,7 @@
using System;
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Field | AttributeTargets.Property)]
public class ES3Serializable : Attribute{}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Field | AttributeTargets.Property)]
public class ES3NonSerializable : Attribute { }

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: ed09c1515c82aa7438f2dc6146085418
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: c5e7cfad151801e4587b8ba4615dbd74
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,55 @@
using UnityEngine;
using System.Collections.Generic;
public class ES3AutoSave : MonoBehaviour, ISerializationCallbackReceiver
{
public bool saveLayer = true;
public bool saveTag = true;
public bool saveName = true;
public bool saveHideFlags = true;
public bool saveActive = true;
public bool saveChildren = false;
private bool isQuitting = false;
//[HideInInspector]
public List<Component> componentsToSave = new List<Component>();
public void Reset()
{
// Initialise saveLayer (etc) to false for all new Components.
saveLayer = false;
saveTag = false;
saveName = false;
saveHideFlags = false;
saveActive = false;
saveChildren = false;
}
public void Awake()
{
if (ES3AutoSaveMgr.Current == null)
ES3Internal.ES3Debug.LogWarning("<b>No GameObjects in this scene will be autosaved</b> because there is no Easy Save 3 Manager. To add a manager to this scene, exit playmode and go to Assets > Easy Save 3 > Add Manager to Scene.", this);
else
ES3AutoSaveMgr.AddAutoSave(this);
}
public void OnApplicationQuit()
{
isQuitting = true;
}
public void OnDestroy()
{
// If this is being destroyed, but not because the application is quitting,
// remove the AutoSave from the manager.
if (!isQuitting)
ES3AutoSaveMgr.RemoveAutoSave(this);
}
public void OnBeforeSerialize() { }
public void OnAfterDeserialize()
{
// Remove any null Components
componentsToSave.RemoveAll(c => c == null || c.GetType() == typeof(Component));
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 132d687c0c0cb9e489632d423b4c376d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,160 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using System.Linq;
#if UNITY_VISUAL_SCRIPTING
[Unity.VisualScripting.IncludeInSettings(true)]
#elif BOLT_VISUAL_SCRIPTING
[Ludiq.IncludeInSettings(true)]
#endif
public class ES3AutoSaveMgr : MonoBehaviour
{
public static ES3AutoSaveMgr _current = null;
public static ES3AutoSaveMgr Current
{
get
{
if (_current == null /*|| _current.gameObject.scene != SceneManager.GetActiveScene()*/)
{
var scene = SceneManager.GetActiveScene();
var roots = scene.GetRootGameObjects();
// First, look for Easy Save 3 Manager in the top-level.
foreach (var root in roots)
if (root.name == "Easy Save 3 Manager")
return _current = root.GetComponent<ES3AutoSaveMgr>();
// If the user has moved or renamed the Easy Save 3 Manager, we need to perform a deep search.
foreach (var root in roots)
if ((_current = root.GetComponentInChildren<ES3AutoSaveMgr>()) != null)
return _current;
}
return _current;
}
}
// Included for backwards compatibility.
public static ES3AutoSaveMgr Instance
{
get { return Current; }
}
public enum LoadEvent { None, Awake, Start }
public enum SaveEvent { None, OnApplicationQuit, OnApplicationPause }
public string key = System.Guid.NewGuid().ToString();
public SaveEvent saveEvent = SaveEvent.OnApplicationQuit;
public LoadEvent loadEvent = LoadEvent.Awake;
public ES3SerializableSettings settings = new ES3SerializableSettings("AutoSave.es3", ES3.Location.Cache);
public HashSet<ES3AutoSave> autoSaves = new HashSet<ES3AutoSave>();
public void Save()
{
if (autoSaves == null || autoSaves.Count == 0)
return;
// If we're using caching and we've not already cached this file, cache it.
if (settings.location == ES3.Location.Cache && !ES3.FileExists(settings))
ES3.CacheFile(settings);
if (autoSaves == null || autoSaves.Count == 0)
{
ES3.DeleteKey(key, settings);
}
else
{
var gameObjects = new List<GameObject>();
foreach (var autoSave in autoSaves)
{
// If the ES3AutoSave component is disabled, don't save it.
if (autoSave != null && autoSave.enabled)
gameObjects.Add(autoSave.gameObject);
}
// Save in the same order as their depth in the hierarchy.
ES3.Save<GameObject[]>(key, gameObjects.OrderBy(x => GetDepth(x.transform)).ToArray(), settings);
}
if(settings.location == ES3.Location.Cache && ES3.FileExists(settings))
ES3.StoreCachedFile(settings);
}
public void Load()
{
try
{
// If we're using caching and we've not already cached this file, cache it.
if (settings.location == ES3.Location.Cache && !ES3.FileExists(settings))
ES3.CacheFile(settings);
}
catch { }
ES3.Load<GameObject[]>(key, new GameObject[0], settings);
}
void Start()
{
if(loadEvent == LoadEvent.Start)
Load();
}
public void Awake()
{
GetAutoSaves();
if (loadEvent == LoadEvent.Awake)
Load();
}
void OnApplicationQuit()
{
if(saveEvent == SaveEvent.OnApplicationQuit)
Save();
}
void OnApplicationPause(bool paused)
{
if( (saveEvent == SaveEvent.OnApplicationPause ||
(Application.isMobilePlatform && saveEvent == SaveEvent.OnApplicationQuit)) && paused)
Save();
}
/* Register an ES3AutoSave with the ES3AutoSaveMgr, if there is one */
public static void AddAutoSave(ES3AutoSave autoSave)
{
if(ES3AutoSaveMgr.Current != null)
ES3AutoSaveMgr.Current.autoSaves.Add(autoSave);
}
/* Remove an ES3AutoSave from the ES3AutoSaveMgr, for example if it's GameObject has been destroyed */
public static void RemoveAutoSave(ES3AutoSave autoSave)
{
if(ES3AutoSaveMgr.Current != null)
ES3AutoSaveMgr.Current.autoSaves.Remove(autoSave);
}
/* Gathers all of the ES3AutoSave Components in the scene and registers them with the manager */
public void GetAutoSaves()
{
autoSaves = new HashSet<ES3AutoSave>();
foreach (var go in this.gameObject.scene.GetRootGameObjects())
autoSaves.UnionWith(go.GetComponentsInChildren<ES3AutoSave>(true));
}
// Gets the depth of a Transform in the hierarchy.
static int GetDepth(Transform t)
{
int depth = 0;
while (t.parent != null)
{
t = t.parent;
depth++;
}
return depth;
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: bc4c084043dc014459977604947a0271
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 5da0e0b897dee2a4f85041d11656a7e4
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,52 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace ES3Internal
{
internal static class ES3Debug
{
private const string disableInfoMsg = "\n<i>To disable these messages from Easy Save, go to Window > Easy Save 3 > Settings, and uncheck 'Log Info'</i>";
private const string disableWarningMsg = "\n<i>To disable warnings from Easy Save, go to Window > Easy Save 3 > Settings, and uncheck 'Log Warnings'</i>";
private const string disableErrorMsg = "\n<i>To disable these error messages from Easy Save, go to Window > Easy Save 3 > Settings, and uncheck 'Log Errors'</i>";
private const char indentChar = '-';
public static void Log(string msg, Object context = null, int indent=0)
{
if (!ES3Settings.defaultSettingsScriptableObject.logDebugInfo)
return;
else if (context != null)
Debug.LogFormat(context, Indent(indent) + msg + disableInfoMsg);
else
Debug.LogFormat(context, Indent(indent) + msg);
}
public static void LogWarning(string msg, Object context=null, int indent = 0)
{
if (!ES3Settings.defaultSettingsScriptableObject.logWarnings)
return;
else if (context != null)
Debug.LogWarningFormat(context, Indent(indent) + msg + disableWarningMsg);
else
Debug.LogWarningFormat(context, Indent(indent) + msg + disableWarningMsg);
}
public static void LogError(string msg, Object context = null, int indent = 0)
{
if (!ES3Settings.defaultSettingsScriptableObject.logErrors)
return;
else if (context != null)
Debug.LogErrorFormat(context, Indent(indent) + msg + disableErrorMsg);
else
Debug.LogErrorFormat(context, Indent(indent) + msg + disableErrorMsg);
}
private static string Indent(int size)
{
if (size < 0)
return "";
return new string(indentChar, size);
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: e8972072d44c5f945879f39db5fd0711
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 76736e9582352734e8ba55170546de81
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,208 @@
#if !DISABLE_ENCRYPTION
using System.IO;
using System.Security.Cryptography;
#if NETFX_CORE
using Windows.Security.Cryptography;
using Windows.Security.Cryptography.Core;
using Windows.Storage.Streams;
using System.Runtime.InteropServices.WindowsRuntime;
#endif
namespace ES3Internal
{
public static class ES3Hash
{
#if NETFX_CORE
public static string SHA1Hash(string input)
{
return System.Text.Encoding.UTF8.GetString(UnityEngine.Windows.Crypto.ComputeSHA1Hash(System.Text.Encoding.UTF8.GetBytes(input)));
}
#else
public static string SHA1Hash(string input)
{
using (SHA1Managed sha1 = new SHA1Managed())
return System.Text.Encoding.UTF8.GetString(sha1.ComputeHash(System.Text.Encoding.UTF8.GetBytes(input)));
}
#endif
}
public abstract class EncryptionAlgorithm
{
public abstract byte[] Encrypt(byte[] bytes, string password, int bufferSize);
public abstract byte[] Decrypt(byte[] bytes, string password, int bufferSize);
public abstract void Encrypt(Stream input, Stream output, string password, int bufferSize);
public abstract void Decrypt(Stream input, Stream output, string password, int bufferSize);
protected static void CopyStream(Stream input, Stream output, int bufferSize)
{
byte[] buffer = new byte[bufferSize];
int read;
while ((read = input.Read(buffer, 0, bufferSize)) > 0)
output.Write(buffer, 0, read);
}
}
public class AESEncryptionAlgorithm : EncryptionAlgorithm
{
private const int ivSize = 16;
private const int keySize = 16;
private const int pwIterations = 100;
public override byte[] Encrypt(byte[] bytes, string password, int bufferSize)
{
using (var input = new MemoryStream(bytes))
{
using (var output = new MemoryStream())
{
Encrypt(input, output, password, bufferSize);
return output.ToArray();
}
}
}
public override byte[] Decrypt(byte[] bytes, string password, int bufferSize)
{
using (var input = new MemoryStream(bytes))
{
using (var output = new MemoryStream())
{
Decrypt(input, output, password, bufferSize);
return output.ToArray();
}
}
}
public override void Encrypt(Stream input, Stream output, string password, int bufferSize)
{
input.Position = 0;
#if NETFX_CORE
// Generate an IV and write it to the output.
var iv = CryptographicBuffer.GenerateRandom(ivSize);
output.Write(iv.ToArray(), 0, ivSize);
var pwBuffer = CryptographicBuffer.ConvertStringToBinary(password, BinaryStringEncoding.Utf8);
var keyDerivationProvider = KeyDerivationAlgorithmProvider.OpenAlgorithm("PBKDF2_SHA1");
KeyDerivationParameters pbkdf2Parms = KeyDerivationParameters.BuildForPbkdf2(iv, pwIterations);
// Create a key based on original key and derivation parmaters
CryptographicKey keyOriginal = keyDerivationProvider.CreateKey(pwBuffer);
IBuffer keyMaterial = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms, keySize);
var provider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7);
var key = provider.CreateSymmetricKey(keyMaterial);
// Get the input stream as an IBuffer.
IBuffer msg;
using(var ms = new MemoryStream())
{
input.CopyTo(ms);
msg = ms.ToArray().AsBuffer();
}
var buffEncrypt = CryptographicEngine.Encrypt(key, msg, iv);
output.Write(buffEncrypt.ToArray(), 0, (int)buffEncrypt.Length);
output.Dispose();
#else
using (var alg = Aes.Create())
{
alg.Mode = CipherMode.CBC;
alg.Padding = PaddingMode.PKCS7;
alg.GenerateIV();
var key = new Rfc2898DeriveBytes(password, alg.IV, pwIterations);
alg.Key = key.GetBytes(keySize);
// Write the IV to the output stream.
output.Write(alg.IV, 0, ivSize);
using(var encryptor = alg.CreateEncryptor())
using(var cs = new CryptoStream(output, encryptor, CryptoStreamMode.Write))
CopyStream(input, cs, bufferSize);
}
#endif
}
public override void Decrypt(Stream input, Stream output, string password, int bufferSize)
{
#if NETFX_CORE
var thisIV = new byte[ivSize];
input.Read(thisIV, 0, ivSize);
var iv = thisIV.AsBuffer();
var pwBuffer = CryptographicBuffer.ConvertStringToBinary(password, BinaryStringEncoding.Utf8);
var keyDerivationProvider = KeyDerivationAlgorithmProvider.OpenAlgorithm("PBKDF2_SHA1");
KeyDerivationParameters pbkdf2Parms = KeyDerivationParameters.BuildForPbkdf2(iv, pwIterations);
// Create a key based on original key and derivation parameters.
CryptographicKey keyOriginal = keyDerivationProvider.CreateKey(pwBuffer);
IBuffer keyMaterial = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms, keySize);
var provider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7);
var key = provider.CreateSymmetricKey(keyMaterial);
// Get the input stream as an IBuffer.
IBuffer msg;
using(var ms = new MemoryStream())
{
input.CopyTo(ms);
msg = ms.ToArray().AsBuffer();
}
var buffDecrypt = CryptographicEngine.Decrypt(key, msg, iv);
output.Write(buffDecrypt.ToArray(), 0, (int)buffDecrypt.Length);
#else
using (var alg = Aes.Create())
{
var thisIV = new byte[ivSize];
input.Read(thisIV, 0, ivSize);
alg.IV = thisIV;
var key = new Rfc2898DeriveBytes(password, alg.IV, pwIterations);
alg.Key = key.GetBytes(keySize);
using(var decryptor = alg.CreateDecryptor())
using(var cryptoStream = new CryptoStream(input, decryptor, CryptoStreamMode.Read))
CopyStream(cryptoStream, output, bufferSize);
}
#endif
output.Position = 0;
}
}
public class UnbufferedCryptoStream : MemoryStream
{
private readonly Stream stream;
private readonly bool isReadStream;
private string password;
private int bufferSize;
private EncryptionAlgorithm alg;
private bool disposed = false;
public UnbufferedCryptoStream(Stream stream, bool isReadStream, string password, int bufferSize, EncryptionAlgorithm alg) : base()
{
this.stream = stream;
this.isReadStream = isReadStream;
this.password = password;
this.bufferSize = bufferSize;
this.alg = alg;
if (isReadStream)
alg.Decrypt(stream, this, password, bufferSize);
}
protected override void Dispose(bool disposing)
{
if (disposed)
return;
disposed = true;
if (!isReadStream)
alg.Encrypt(this, stream, password, bufferSize);
stream.Dispose();
base.Dispose(disposing);
}
}
}
#endif

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 17f1525fffc9e7647b3aba297290ed33
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,516 @@
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System;
using ES3Types;
using UnityEngine;
using ES3Internal;
using System.Linq;
/// <summary>Represents a cached file which can be saved to and loaded from, and commited to storage when necessary.</summary>
public class ES3File
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public static Dictionary<string, ES3File> cachedFiles = new Dictionary<string, ES3File>();
public ES3Settings settings;
private Dictionary<string, ES3Data> cache = new Dictionary<string, ES3Data>();
private bool syncWithFile = false;
private DateTime timestamp = DateTime.UtcNow;
/// <summary>Creates a new ES3File and loads the default file into the ES3File if there is data to load.</summary>
public ES3File() : this(new ES3Settings(), true) { }
/// <summary>Creates a new ES3File and loads the specified file into the ES3File if there is data to load.</summary>
/// <param name="filepath">The relative or absolute path of the file in storage our ES3File is associated with.</param>
public ES3File(string filePath) : this(new ES3Settings(filePath), true) { }
/// <summary>Creates a new ES3File and loads the specified file into the ES3File if there is data to load.</summary>
/// <param name="filepath">The relative or absolute path of the file in storage our ES3File is associated with.</param>
/// <param name="settings">The settings we want to use to override the default settings.</param>
public ES3File(string filePath, ES3Settings settings) : this(new ES3Settings(filePath, settings), true) { }
/// <summary>Creates a new ES3File and loads the specified file into the ES3File if there is data to load.</summary>
/// <param name="settings">The settings we want to use to override the default settings.</param>
public ES3File(ES3Settings settings) : this(settings, true) { }
/// <summary>Creates a new ES3File and only loads the default file into it if syncWithFile is set to true.</summary>
/// <param name="syncWithFile">Whether we should sync this ES3File with the one in storage immediately after creating it.</param>
public ES3File(bool syncWithFile) : this(new ES3Settings(), syncWithFile) { }
/// <summary>Creates a new ES3File and only loads the specified file into it if syncWithFile is set to true.</summary>
/// <param name="filepath">The relative or absolute path of the file in storage our ES3File is associated with.</param>
/// <param name="syncWithFile">Whether we should sync this ES3File with the one in storage immediately after creating it.</param>
public ES3File(string filePath, bool syncWithFile) : this(new ES3Settings(filePath), syncWithFile) { }
/// <summary>Creates a new ES3File and only loads the specified file into it if syncWithFile is set to true.</summary>
/// <param name="filepath">The relative or absolute path of the file in storage our ES3File is associated with.</param>
/// <param name="settings">The settings we want to use to override the default settings.</param>
/// <param name="syncWithFile">Whether we should sync this ES3File with the one in storage immediately after creating it.</param>
public ES3File(string filePath, ES3Settings settings, bool syncWithFile) : this(new ES3Settings(filePath, settings), syncWithFile) { }
/// <summary>Creates a new ES3File and loads the specified file into the ES3File if there is data to load.</summary>
/// <param name="settings">The settings we want to use to override the default settings.</param>
/// <param name="syncWithFile">Whether we should sync this ES3File with the one in storage immediately after creating it.</param>
public ES3File(ES3Settings settings, bool syncWithFile)
{
this.settings = settings;
this.syncWithFile = syncWithFile;
if (syncWithFile)
{
// Type checking must be enabled when syncing.
var settingsWithTypeChecking = (ES3Settings)settings.Clone();
settingsWithTypeChecking.typeChecking = true;
using (var reader = ES3Reader.Create(settingsWithTypeChecking))
{
if (reader == null)
return;
foreach (KeyValuePair<string, ES3Data> kvp in reader.RawEnumerator)
cache[kvp.Key] = kvp.Value;
}
timestamp = ES3.GetTimestamp(settingsWithTypeChecking);
}
}
/// <summary>Creates a new ES3File and loads the bytes into the ES3File. Note the bytes must represent that of a file.</summary>
/// <param name="bytes">The bytes representing our file.</param>
/// <param name="settings">The settings we want to use to override the default settings.</param>
/// <param name="syncWithFile">Whether we should sync this ES3File with the one in storage immediately after creating it.</param>
public ES3File(byte[] bytes, ES3Settings settings = null)
{
if (settings == null)
this.settings = new ES3Settings();
else
this.settings = settings;
syncWithFile = true; // This ensures that the file won't be merged, which would prevent deleted keys from being deleted.
SaveRaw(bytes, settings);
}
/// <summary>Synchronises this ES3File with a file in storage.</summary>
public void Sync()
{
Sync(this.settings);
}
/// <summary>Synchronises this ES3File with a file in storage.</summary>
/// <param name="filepath">The relative or absolute path of the file in storage we want to synchronise with.</param>
/// <param name="settings">The settings we want to use to override the default settings.</param>
public void Sync(string filePath, ES3Settings settings = null)
{
Sync(new ES3Settings(filePath, settings));
}
/// <summary>Synchronises this ES3File with a file in storage.</summary>
/// <param name="settings">The settings we want to use to override the default settings.</param>
public void Sync(ES3Settings settings = null)
{
if (settings == null)
settings = new ES3Settings();
if (cache.Count == 0)
{
ES3.DeleteFile(settings);
return;
}
using (var baseWriter = ES3Writer.Create(settings, true, !syncWithFile, false))
{
foreach (var kvp in cache)
{
// If we change the name of a type, the type may be null.
// In this case, use System.Object as the type.
Type type;
if (kvp.Value.type == null)
type = typeof(System.Object);
else
type = kvp.Value.type.type;
baseWriter.Write(kvp.Key, type, kvp.Value.bytes);
}
baseWriter.Save(!syncWithFile);
}
}
/// <summary>Removes the data stored in this ES3File. The ES3File will be empty after calling this method.</summary>
public void Clear()
{
cache.Clear();
}
/// <summary>Returns an array of all of the key names in this ES3File.</summary>
public string[] GetKeys()
{
var keyCollection = cache.Keys;
var keys = new string[keyCollection.Count];
keyCollection.CopyTo(keys, 0);
return keys;
}
#region Save Methods
/// <summary>Saves a value to a key in this ES3File.</summary>
/// <param name="key">The key we want to use to identify our value in the file.</param>
/// <param name="value">The value we want to save.</param>
public void Save<T>(string key, T value)
{
var unencryptedSettings = (ES3Settings)settings.Clone();
unencryptedSettings.encryptionType = ES3.EncryptionType.None;
unencryptedSettings.compressionType = ES3.CompressionType.None;
// If T is object, use the value to get it's type. Otherwise, use T so that it works with inheritence.
Type type;
if (value == null)
type = typeof(T);
else
type = value.GetType();
cache[key] = new ES3Data(ES3TypeMgr.GetOrCreateES3Type(type), ES3.Serialize(value, unencryptedSettings));
}
/// <summary>Merges the data specified by the bytes parameter into this ES3File.</summary>
/// <param name="bytes">The bytes we want to merge with this ES3File.</param>
/// <param name="settings">The settings we want to use to override the default settings.</param>
public void SaveRaw(byte[] bytes, ES3Settings settings = null)
{
if (settings == null)
settings = new ES3Settings();
// Type checking must be enabled when syncing.
var settingsWithTypeChecking = (ES3Settings)settings.Clone();
settingsWithTypeChecking.typeChecking = true;
using (var reader = ES3Reader.Create(bytes, settingsWithTypeChecking))
{
if (reader == null)
return;
foreach (KeyValuePair<string, ES3Data> kvp in reader.RawEnumerator)
cache[kvp.Key] = kvp.Value;
}
}
/// <summary>Merges the data specified by the bytes parameter into this ES3File.</summary>
/// <param name="bytes">The bytes we want to merge with this ES3File.</param>
/// <param name="settings">The settings we want to use to override the default settings.</param>
public void AppendRaw(byte[] bytes, ES3Settings settings = null)
{
if (settings == null)
settings = new ES3Settings();
// AppendRaw just does the same thing as SaveRaw in ES3File.
SaveRaw(bytes, settings);
}
#endregion
#region Load Methods
/* Standard load methods */
/// <summary>Loads the value from this ES3File with the given key.</summary>
/// <param name="key">The key which identifies the value we want to load.</param>
public object Load(string key)
{
return Load<object>(key);
}
/// <summary>Loads the value from this ES3File with the given key.</summary>
/// <param name="key">The key which identifies the value we want to load.</param>
/// <param name="defaultValue">The value we want to return if the key does not exist in this ES3File.</param>
public object Load(string key, object defaultValue)
{
return Load<object>(key, defaultValue);
}
/// <summary>Loads the value from this ES3File with the given key.</summary>
/// <param name="key">The key which identifies the value we want to load.</param>
public T Load<T>(string key)
{
ES3Data es3Data;
if (!cache.TryGetValue(key, out es3Data))
throw new KeyNotFoundException("Key \"" + key + "\" was not found in this ES3File. Use Load<T>(key, defaultValue) if you want to return a default value if the key does not exist.");
var unencryptedSettings = (ES3Settings)this.settings.Clone();
unencryptedSettings.encryptionType = ES3.EncryptionType.None;
unencryptedSettings.compressionType = ES3.CompressionType.None;
if (typeof(T) == typeof(object))
return (T)ES3.Deserialize(es3Data.type, es3Data.bytes, unencryptedSettings);
return ES3.Deserialize<T>(es3Data.bytes, unencryptedSettings);
}
/// <summary>Loads the value from this ES3File with the given key.</summary>
/// <param name="key">The key which identifies the value we want to load.</param>
/// <param name="defaultValue">The value we want to return if the key does not exist in this ES3File.</param>
public T Load<T>(string key, T defaultValue)
{
ES3Data es3Data;
if (!cache.TryGetValue(key, out es3Data))
return defaultValue;
var unencryptedSettings = (ES3Settings)this.settings.Clone();
unencryptedSettings.encryptionType = ES3.EncryptionType.None;
unencryptedSettings.compressionType = ES3.CompressionType.None;
if (typeof(T) == typeof(object))
return (T)ES3.Deserialize(es3Data.type, es3Data.bytes, unencryptedSettings);
return ES3.Deserialize<T>(es3Data.bytes, unencryptedSettings);
}
/// <summary>Loads the value from this ES3File with the given key into an existing object.</summary>
/// <param name="key">The key which identifies the value we want to load.</param>
/// <param name="obj">The object we want to load the value into.</param>
public void LoadInto<T>(string key, T obj) where T : class
{
ES3Data es3Data;
if (!cache.TryGetValue(key, out es3Data))
throw new KeyNotFoundException("Key \"" + key + "\" was not found in this ES3File. Use Load<T>(key, defaultValue) if you want to return a default value if the key does not exist.");
var unencryptedSettings = (ES3Settings)this.settings.Clone();
unencryptedSettings.encryptionType = ES3.EncryptionType.None;
unencryptedSettings.compressionType = ES3.CompressionType.None;
if (typeof(T) == typeof(object))
ES3.DeserializeInto(es3Data.type, es3Data.bytes, obj, unencryptedSettings);
else
ES3.DeserializeInto(es3Data.bytes, obj, unencryptedSettings);
}
#endregion
#region Load Raw Methods
/// <summary>Loads the ES3File as a raw, unencrypted, uncompressed byte array.</summary>
public byte[] LoadRawBytes()
{
var newSettings = (ES3Settings)settings.Clone();
if (!newSettings.postprocessRawCachedData)
{
newSettings.encryptionType = ES3.EncryptionType.None;
newSettings.compressionType = ES3.CompressionType.None;
}
return GetBytes(newSettings);
}
/// <summary>Loads the ES3File as a raw, unencrypted, uncompressed string, using the encoding defined in the ES3File's settings variable.</summary>
public string LoadRawString()
{
if (cache.Count == 0)
return "";
return settings.encoding.GetString(LoadRawBytes());
}
/*
* Same as LoadRawString, except it will return an encrypted/compressed file if these are enabled.
*/
internal byte[] GetBytes(ES3Settings settings = null)
{
if (cache.Count == 0)
return new byte[0];
if (settings == null)
settings = this.settings;
using (var ms = new System.IO.MemoryStream())
{
var memorySettings = (ES3Settings)settings.Clone();
memorySettings.location = ES3.Location.InternalMS;
// Ensure we return unencrypted bytes.
if (!memorySettings.postprocessRawCachedData)
{
memorySettings.encryptionType = ES3.EncryptionType.None;
memorySettings.compressionType = ES3.CompressionType.None;
}
using (var baseWriter = ES3Writer.Create(ES3Stream.CreateStream(ms, memorySettings, ES3FileMode.Write), memorySettings, true, false))
{
foreach (var kvp in cache)
baseWriter.Write(kvp.Key, kvp.Value.type.type, kvp.Value.bytes);
baseWriter.Save(false);
}
return ms.ToArray();
}
}
#endregion
#region Other ES3 Methods
/// <summary>Deletes a key from this ES3File.</summary>
/// <param name="key">The key we want to delete.</param>
public void DeleteKey(string key)
{
cache.Remove(key);
}
/// <summary>Checks whether a key exists in this ES3File.</summary>
/// <param name="key">The key we want to check the existence of.</param>
/// <returns>True if the key exists, otherwise False.</returns>
public bool KeyExists(string key)
{
return cache.ContainsKey(key);
}
/// <summary>Gets the size of the cached data in bytes.</summary>
public int Size()
{
int size = 0;
foreach (var kvp in cache)
size += kvp.Value.bytes.Length;
return size;
}
public Type GetKeyType(string key)
{
ES3Data es3data;
if (!cache.TryGetValue(key, out es3data))
throw new KeyNotFoundException("Key \"" + key + "\" was not found in this ES3File. Use Load<T>(key, defaultValue) if you want to return a default value if the key does not exist.");
return es3data.type.type;
}
#endregion
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
internal static ES3File GetOrCreateCachedFile(ES3Settings settings)
{
ES3File cachedFile;
if (!cachedFiles.TryGetValue(settings.path, out cachedFile))
{
cachedFile = new ES3File(settings, false);
cachedFiles.Add(settings.path, cachedFile);
cachedFile.syncWithFile = true; // This ensures that the file won't be merged, which would prevent deleted keys from being deleted.
}
// Settings might refer to the same file, but might have changed.
// To account for this, we update the settings of the ES3File each time we access it.
cachedFile.settings = settings;
return cachedFile;
}
internal static void CacheFile(ES3Settings settings)
{
// If we're still using cached settings, set it to the default location.
if (settings.location == ES3.Location.Cache)
{
settings = (ES3Settings)settings.Clone();
// If the default settings are also set to cache, assume ES3.Location.File. Otherwise, set it to the default location.
settings.location = ES3Settings.defaultSettings.location == ES3.Location.Cache ? ES3.Location.File : ES3Settings.defaultSettings.location;
}
if (!ES3.FileExists(settings))
return;
// Disable compression and encryption when loading the raw bytes, and the ES3File constructor will expect encrypted/compressed bytes.
var loadSettings = (ES3Settings)settings.Clone();
loadSettings.compressionType = ES3.CompressionType.None;
loadSettings.encryptionType = ES3.EncryptionType.None;
cachedFiles[settings.path] = new ES3File(ES3.LoadRawBytes(loadSettings), settings);
}
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
internal static void Store(ES3Settings settings = null)
{
if (settings == null)
settings = new ES3Settings(ES3.Location.File);
// If we're still using cached settings, set it to the default location.
else if (settings.location == ES3.Location.Cache)
{
settings = (ES3Settings)settings.Clone();
// If the default settings are also set to cache, assume ES3.Location.File. Otherwise, set it to the default location.
settings.location = ES3Settings.defaultSettings.location == ES3.Location.Cache ? ES3.Location.File : ES3Settings.defaultSettings.location;
}
ES3File cachedFile;
if (!cachedFiles.TryGetValue(settings.path, out cachedFile))
throw new FileNotFoundException("The file '" + settings.path + "' could not be stored because it could not be found in the cache.");
cachedFile.Sync(settings);
}
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
internal static void RemoveCachedFile(ES3Settings settings)
{
cachedFiles.Remove(settings.path);
}
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
internal static void CopyCachedFile(ES3Settings oldSettings, ES3Settings newSettings)
{
ES3File cachedFile;
if (!cachedFiles.TryGetValue(oldSettings.path, out cachedFile))
throw new FileNotFoundException("The file '" + oldSettings.path + "' could not be copied because it could not be found in the cache.");
if (cachedFiles.ContainsKey(newSettings.path))
throw new InvalidOperationException("Cannot copy file '" + oldSettings.path + "' to '" + newSettings.path + "' because '" + newSettings.path + "' already exists");
cachedFiles.Add(newSettings.path, (ES3File)cachedFile.MemberwiseClone());
}
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
internal static void DeleteKey(string key, ES3Settings settings)
{
ES3File cachedFile;
if (cachedFiles.TryGetValue(settings.path, out cachedFile))
cachedFile.DeleteKey(key);
}
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
internal static bool KeyExists(string key, ES3Settings settings)
{
ES3File cachedFile;
if (cachedFiles.TryGetValue(settings.path, out cachedFile))
return cachedFile.KeyExists(key);
return false;
}
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
internal static bool FileExists(ES3Settings settings)
{
return cachedFiles.ContainsKey(settings.path);
}
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
internal static string[] GetKeys(ES3Settings settings)
{
ES3File cachedFile;
if (!cachedFiles.TryGetValue(settings.path, out cachedFile))
throw new FileNotFoundException("Could not get keys from the file '" + settings.path + "' because it could not be found in the cache.");
return cachedFile.cache.Keys.ToArray();
}
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
internal static string[] GetFiles()
{
return cachedFiles.Keys.ToArray();
}
internal static DateTime GetTimestamp(ES3Settings settings)
{
ES3File cachedFile;
if (!cachedFiles.TryGetValue(settings.path, out cachedFile))
return new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
return cachedFile.timestamp;
}
}
namespace ES3Internal
{
public struct ES3Data
{
public ES3Type type;
public byte[] bytes;
public ES3Data(Type type, byte[] bytes)
{
this.type = type == null ? null : ES3TypeMgr.GetOrCreateES3Type(type);
this.bytes = bytes;
}
public ES3Data(ES3Type type, byte[] bytes)
{
this.type = type;
this.bytes = bytes;
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: b440b2568aee31f4ba9da59780f53abc
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,20 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[ExecuteInEditMode]
public class ES3GameObject : MonoBehaviour
{
public List<Component> components = new List<Component>();
/* Ensures that this Component is always last in the List to guarantee that it's loaded after any Components it references */
private void Update()
{
if (Application.isPlaying)
return;
#if UNITY_EDITOR
UnityEditorInternal.ComponentUtility.MoveComponentDown(this);
#endif
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: c57ae9ded6c6fe443af44501f3208f8a
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,178 @@
using System.IO;
using System;
using UnityEngine;
namespace ES3Internal
{
public static class ES3IO
{
#if UNITY_SWITCH
internal static readonly string persistentDataPath = "";
internal static readonly string dataPath = "";
#else
internal static readonly string persistentDataPath = Application.persistentDataPath;
internal static readonly string dataPath = Application.dataPath;
#endif
internal const string backupFileSuffix = ".bac";
internal const string temporaryFileSuffix = ".tmp";
public enum ES3FileMode { Read, Write, Append }
public static DateTime GetTimestamp(string filePath)
{
if (!FileExists(filePath))
return new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
return File.GetLastWriteTime(filePath).ToUniversalTime();
}
public static string GetExtension(string path)
{
return Path.GetExtension(path);
}
public static void DeleteFile(string filePath)
{
if (FileExists(filePath))
File.Delete(filePath);
}
public static bool FileExists(string filePath) { return File.Exists(filePath); }
public static void MoveFile(string sourcePath, string destPath) { File.Move(sourcePath, destPath); }
public static void CopyFile(string sourcePath, string destPath) { File.Copy(sourcePath, destPath); }
public static void MoveDirectory(string sourcePath, string destPath) { Directory.Move(sourcePath, destPath); }
public static void CreateDirectory(string directoryPath) { Directory.CreateDirectory(directoryPath); }
public static bool DirectoryExists(string directoryPath) { return Directory.Exists(directoryPath); }
/*
* Given a path, it returns the directory that path points to.
* eg. "C:/myFolder/thisFolder/myFile.txt" will return "C:/myFolder/thisFolder".
*/
public static string GetDirectoryPath(string path, char seperator = '/')
{
//return Path.GetDirectoryName(path);
// Path.GetDirectoryName turns forward slashes to backslashes in some cases on Windows, which is why
// Substring is used instead.
char slashChar = UsesForwardSlash(path) ? '/' : '\\';
int slash = path.LastIndexOf(slashChar);
// If this path ends in a slash it is assumed to already be a path to a Directory.
if (slash == path.Length - 1)
return path;
// Ignore trailing slash if necessary.
if (slash == (path.Length - 1))
slash = path.Substring(0, slash).LastIndexOf(slashChar);
if (slash == -1)
ES3Debug.LogError("Path provided is not a directory path as it contains no slashes.");
return path.Substring(0, slash);
}
public static bool UsesForwardSlash(string path)
{
if (path.Contains("/"))
return true;
return false;
}
// Takes a directory path and a file or directory name and combines them into a single path.
public static string CombinePathAndFilename(string directoryPath, string fileOrDirectoryName)
{
if (directoryPath[directoryPath.Length - 1] != '/' && directoryPath[directoryPath.Length - 1] != '\\')
directoryPath += '/';
return directoryPath + fileOrDirectoryName;
}
public static string[] GetDirectories(string path, bool getFullPaths = true)
{
var paths = Directory.GetDirectories(path);
for (int i = 0; i < paths.Length; i++)
{
if (!getFullPaths)
paths[i] = Path.GetFileName(paths[i]);
// GetDirectories sometimes returns backslashes, so we need to convert them to
// forward slashes.
paths[i].Replace("\\", "/");
}
return paths;
}
public static void DeleteDirectory(string directoryPath)
{
if (DirectoryExists(directoryPath))
Directory.Delete(directoryPath, true);
}
// Note: Paths not ending in a slash are assumed to be a path to a file.
// In this case the Directory containing the file will be searched.
public static string[] GetFiles(string path, bool getFullPaths = true)
{
var paths = Directory.GetFiles(GetDirectoryPath(path));
if (!getFullPaths)
{
for (int i = 0; i < paths.Length; i++)
paths[i] = Path.GetFileName(paths[i]);
}
return paths;
}
public static byte[] ReadAllBytes(string path)
{
return File.ReadAllBytes(path);
}
public static void WriteAllBytes(string path, byte[] bytes)
{
File.WriteAllBytes(path, bytes);
}
public static void CommitBackup(ES3Settings settings)
{
ES3Debug.Log("Committing backup for " + settings.path + " to storage location " + settings.location);
var temporaryFilePath = settings.FullPath + temporaryFileSuffix;
if (settings.location == ES3.Location.File)
{
var oldFileBackup = settings.FullPath + temporaryFileSuffix + ".bak";
// If there's existing save data to overwrite ...
if (FileExists(settings.FullPath))
{
// Delete any old backups.
DeleteFile(oldFileBackup);
// Rename the old file so we can restore it if it fails.
CopyFile(settings.FullPath, oldFileBackup);
try
{
// Delete the old file so that we can move it.
DeleteFile(settings.FullPath);
// Now rename the temporary file to the name of the save file.
MoveFile(temporaryFilePath, settings.FullPath);
}
catch (Exception e)
{
// If any exceptions occur, restore the original save file.
try { DeleteFile(settings.FullPath); } catch { }
MoveFile(oldFileBackup, settings.FullPath);
throw e;
}
DeleteFile(oldFileBackup);
}
// Else just rename the temporary file to the main file.
else
MoveFile(temporaryFilePath, settings.FullPath);
}
else if (settings.location == ES3.Location.PlayerPrefs)
{
PlayerPrefs.SetString(settings.FullPath, PlayerPrefs.GetString(temporaryFilePath));
PlayerPrefs.DeleteKey(temporaryFilePath);
PlayerPrefs.Save();
}
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 384defb640bb5cc429878919bc66bfed
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,19 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/*
* Displays an info message in the inspector.
* Only available in the Editor.
*/
public class ES3InspectorInfo : MonoBehaviour
{
#if UNITY_EDITOR
public string message = "";
public void SetMessage(string message)
{
this.message = message;
}
#endif
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 1d1f89293f50fdf4e813a8d554d6d135
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

Some files were not shown because too many files have changed in this diff Show More