aboutsummaryrefslogtreecommitdiff
path: root/Assets/Cinemachine/Base/Editor/Utility
diff options
context:
space:
mode:
authorTom Harley2018-09-03 23:34:21 +0100
committerTom Harley2018-09-03 23:36:01 +0100
commit5440734d820606b29a795c46172ade5d7eba8efb (patch)
tree85867f40afb02cfa2a5028b515ed0a195866b7e9 /Assets/Cinemachine/Base/Editor/Utility
downloadpowerless-5440734d820606b29a795c46172ade5d7eba8efb.tar.gz
powerless-5440734d820606b29a795c46172ade5d7eba8efb.zip

Initial commit

Diffstat (limited to 'Assets/Cinemachine/Base/Editor/Utility')
-rw-r--r--Assets/Cinemachine/Base/Editor/Utility/BaseEditor.cs79
-rw-r--r--Assets/Cinemachine/Base/Editor/Utility/BaseEditor.cs.meta12
-rw-r--r--Assets/Cinemachine/Base/Editor/Utility/EmbeddedAssetHelpers.cs177
-rw-r--r--Assets/Cinemachine/Base/Editor/Utility/EmbeddedAssetHelpers.cs.meta12
-rw-r--r--Assets/Cinemachine/Base/Editor/Utility/SaveDuringPlay.cs529
-rw-r--r--Assets/Cinemachine/Base/Editor/Utility/SaveDuringPlay.cs.meta12
-rw-r--r--Assets/Cinemachine/Base/Editor/Utility/ScriptableObjectUtility.cs160
-rw-r--r--Assets/Cinemachine/Base/Editor/Utility/ScriptableObjectUtility.cs.meta12
-rw-r--r--Assets/Cinemachine/Base/Editor/Utility/SerializedPropertyHelper.cs59
-rw-r--r--Assets/Cinemachine/Base/Editor/Utility/SerializedPropertyHelper.cs.meta12
10 files changed, 1064 insertions, 0 deletions
diff --git a/Assets/Cinemachine/Base/Editor/Utility/BaseEditor.cs b/Assets/Cinemachine/Base/Editor/Utility/BaseEditor.cs
new file mode 100644
index 0000000..88d37ff
--- /dev/null
+++ b/Assets/Cinemachine/Base/Editor/Utility/BaseEditor.cs
@@ -0,0 +1,79 @@
+using UnityEditor;
+using System;
+using System.Collections.Generic;
+using Cinemachine.Utility;
+using System.Linq.Expressions;
+
+namespace Cinemachine.Editor
+{
+ public class BaseEditor<T> : UnityEditor.Editor where T : class
+ {
+ protected T Target { get { return target as T; } }
+
+ protected SerializedProperty FindAndExcludeProperty<TValue>(Expression<Func<T, TValue>> expr)
+ {
+ SerializedProperty p = FindProperty(expr);
+ ExcludeProperty(p.name);
+ return p;
+ }
+
+ protected SerializedProperty FindProperty<TValue>(Expression<Func<T, TValue>> expr)
+ {
+ return serializedObject.FindProperty(FieldPath(expr));
+ }
+
+ protected string FieldPath<TValue>(Expression<Func<T, TValue>> expr)
+ {
+ return ReflectionHelpers.GetFieldPath(expr);
+ }
+
+ protected virtual List<string> GetExcludedPropertiesInInspector()
+ {
+ var excluded = new List<string>() { "m_Script" };
+ if (mAdditionalExcluded != null)
+ excluded.AddRange(mAdditionalExcluded);
+ return excluded;
+ }
+
+ List<string> mAdditionalExcluded;
+ protected void ExcludeProperty(string propertyName)
+ {
+ if (mAdditionalExcluded == null)
+ mAdditionalExcluded = new List<string>();
+ mAdditionalExcluded.Add(propertyName);
+ }
+
+ public override void OnInspectorGUI()
+ {
+ BeginInspector();
+ DrawRemainingPropertiesInInspector();
+ }
+
+ protected virtual void BeginInspector()
+ {
+ mAdditionalExcluded = null;
+ serializedObject.Update();
+ }
+
+ protected virtual void DrawPropertyInInspector(SerializedProperty p)
+ {
+ List<string> excluded = GetExcludedPropertiesInInspector();
+ if (!excluded.Contains(p.name))
+ {
+ EditorGUI.BeginChangeCheck();
+ EditorGUILayout.PropertyField(p);
+ if (EditorGUI.EndChangeCheck())
+ serializedObject.ApplyModifiedProperties();
+ ExcludeProperty(p.name);
+ }
+ }
+
+ protected void DrawRemainingPropertiesInInspector()
+ {
+ EditorGUI.BeginChangeCheck();
+ DrawPropertiesExcluding(serializedObject, GetExcludedPropertiesInInspector().ToArray());
+ if (EditorGUI.EndChangeCheck())
+ serializedObject.ApplyModifiedProperties();
+ }
+ }
+}
diff --git a/Assets/Cinemachine/Base/Editor/Utility/BaseEditor.cs.meta b/Assets/Cinemachine/Base/Editor/Utility/BaseEditor.cs.meta
new file mode 100644
index 0000000..2878dd7
--- /dev/null
+++ b/Assets/Cinemachine/Base/Editor/Utility/BaseEditor.cs.meta
@@ -0,0 +1,12 @@
+fileFormatVersion: 2
+guid: 15ef94834d9e4aa44ac8fe619843346b
+timeCreated: 1506620939
+licenseType: Store
+MonoImporter:
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Assets/Cinemachine/Base/Editor/Utility/EmbeddedAssetHelpers.cs b/Assets/Cinemachine/Base/Editor/Utility/EmbeddedAssetHelpers.cs
new file mode 100644
index 0000000..ee99023
--- /dev/null
+++ b/Assets/Cinemachine/Base/Editor/Utility/EmbeddedAssetHelpers.cs
@@ -0,0 +1,177 @@
+using UnityEngine;
+using UnityEditor;
+using System;
+
+namespace Cinemachine.Editor
+{
+ /// <summary>
+ /// Helper for drawing embedded asset editors
+ /// </summary>
+ public class EmbeddeAssetEditor<T> where T : ScriptableObject
+ {
+ /// <summary>
+ /// Create in OnEnable()
+ /// </summary>
+ public EmbeddeAssetEditor(string propertyName, UnityEditor.Editor owner)
+ {
+ m_PropertyName = propertyName;
+ m_Owner = owner;
+ m_DoVersionControlChecks = UnityEditor.VersionControl.Provider.isActive;
+ m_CreateButtonGUIContent = new GUIContent(
+ "Create Asset", "Create a new shared settings asset");
+ }
+
+ /// <summary>
+ /// Called after the asset editor is created, in case it needs
+ /// to be customized
+ /// </summary>
+ public OnCreateEditorDelegate OnCreateEditor;
+ public delegate void OnCreateEditorDelegate(UnityEditor.Editor editor);
+
+ /// <summary>
+ /// Called when the asset being edited was changed by the user.
+ /// </summary>
+ public OnChangedDelegate OnChanged;
+ public delegate void OnChangedDelegate(T obj);
+
+ /// <summary>
+ /// Free the resources in OnDisable()
+ /// </summary>
+ public void OnDisable()
+ {
+ DestroyEditor();
+ m_Owner = null;
+ }
+
+ /// <summary>
+ /// Customize this after creation if you want
+ /// </summary>
+ public GUIContent m_CreateButtonGUIContent;
+
+ private string m_PropertyName;
+ private UnityEditor.Editor m_Editor = null;
+ private UnityEditor.Editor m_Owner = null;
+ private bool m_DoVersionControlChecks = false;
+
+ const int kIndentOffset = 6;
+
+ /// <summary>
+ /// Call this from OnInspectorGUI. Will draw the asset reference field, and
+ /// the embedded editor, or a Create Asset button, if no asset is set.
+ /// </summary>
+ public void DrawEditorCombo(
+ string title, string defaultName, string extension, string message,
+ string showLabel, bool indent)
+ {
+ SerializedProperty property = m_Owner.serializedObject.FindProperty(m_PropertyName);
+ if (m_Editor == null)
+ UpdateEditor();
+ if (m_Editor == null)
+ AssetFieldWithCreateButton(property, title, defaultName, extension, message);
+ else
+ {
+ EditorGUILayout.BeginVertical(GUI.skin.box);
+ Rect rect = EditorGUILayout.GetControlRect(true);
+ rect.height = EditorGUIUtility.singleLineHeight;
+ EditorGUI.BeginChangeCheck();
+ EditorGUI.PropertyField(rect, property);
+ if (EditorGUI.EndChangeCheck())
+ {
+ m_Owner.serializedObject.ApplyModifiedProperties();
+ UpdateEditor();
+ }
+ if (m_Editor != null)
+ {
+ Rect foldoutRect = new Rect(
+ rect.x - kIndentOffset, rect.y, rect.width + kIndentOffset, rect.height);
+ property.isExpanded = EditorGUI.Foldout(
+ foldoutRect, property.isExpanded, GUIContent.none);
+
+ UnityEditor.VersionControl.Asset targetAsset
+ = UnityEditor.VersionControl.Provider.GetAssetByPath(
+ AssetDatabase.GetAssetPath(m_Editor.target));
+ bool isLockedFile = m_DoVersionControlChecks
+ && !targetAsset.IsOneOfStates(new[] {
+ UnityEditor.VersionControl.Asset.States.CheckedOutLocal,
+ UnityEditor.VersionControl.Asset.States.AddedLocal,
+ });
+
+ GUI.enabled = !isLockedFile;
+ if (property.isExpanded)
+ {
+ EditorGUILayout.Separator();
+ EditorGUILayout.HelpBox(
+ "This is a shared asset. Changes made here will apply to all users of this asset.",
+ MessageType.Info);
+ EditorGUI.BeginChangeCheck();
+ if (indent)
+ ++EditorGUI.indentLevel;
+ m_Editor.OnInspectorGUI();
+ if (indent)
+ --EditorGUI.indentLevel;
+ if (EditorGUI.EndChangeCheck() && (OnChanged != null))
+ OnChanged(property.objectReferenceValue as T);
+ }
+ GUI.enabled = true;
+ if (isLockedFile && GUILayout.Button("Check out"))
+ {
+ UnityEditor.VersionControl.Provider.Checkout(
+ targetAsset, UnityEditor.VersionControl.CheckoutMode.Both);
+ }
+ }
+ EditorGUILayout.EndVertical();
+ }
+ }
+
+ private void AssetFieldWithCreateButton(
+ SerializedProperty property,
+ string title, string defaultName, string extension, string message)
+ {
+ EditorGUI.BeginChangeCheck();
+
+ float hSpace = 5;
+ float buttonWidth = GUI.skin.button.CalcSize(m_CreateButtonGUIContent).x;
+ Rect r = EditorGUILayout.GetControlRect(true);
+ r.width -= buttonWidth + hSpace;
+ EditorGUI.PropertyField(r, property);
+ r.x += r.width + hSpace; r.width = buttonWidth;
+ if (GUI.Button(r, m_CreateButtonGUIContent))
+ {
+ string newAssetPath = EditorUtility.SaveFilePanelInProject(
+ title, defaultName, extension, message);
+ if (!string.IsNullOrEmpty(newAssetPath))
+ {
+ T asset = ScriptableObjectUtility.CreateAt<T>(newAssetPath);
+ property.objectReferenceValue = asset;
+ m_Owner.serializedObject.ApplyModifiedProperties();
+ }
+ }
+ if (EditorGUI.EndChangeCheck())
+ {
+ m_Owner.serializedObject.ApplyModifiedProperties();
+ UpdateEditor();
+ }
+ }
+
+ public void DestroyEditor()
+ {
+ if (m_Editor != null)
+ {
+ UnityEngine.Object.DestroyImmediate(m_Editor);
+ m_Editor = null;
+ }
+ }
+
+ public void UpdateEditor()
+ {
+ DestroyEditor();
+ SerializedProperty property = m_Owner.serializedObject.FindProperty(m_PropertyName);
+ if (property.objectReferenceValue != null)
+ {
+ m_Editor = UnityEditor.Editor.CreateEditor(property.objectReferenceValue);
+ if (OnCreateEditor != null)
+ OnCreateEditor(m_Editor);
+ }
+ }
+ }
+}
diff --git a/Assets/Cinemachine/Base/Editor/Utility/EmbeddedAssetHelpers.cs.meta b/Assets/Cinemachine/Base/Editor/Utility/EmbeddedAssetHelpers.cs.meta
new file mode 100644
index 0000000..4292865
--- /dev/null
+++ b/Assets/Cinemachine/Base/Editor/Utility/EmbeddedAssetHelpers.cs.meta
@@ -0,0 +1,12 @@
+fileFormatVersion: 2
+guid: d30409ab90458e5409807c8b0274ac9c
+timeCreated: 1484084529
+licenseType: Store
+MonoImporter:
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Assets/Cinemachine/Base/Editor/Utility/SaveDuringPlay.cs b/Assets/Cinemachine/Base/Editor/Utility/SaveDuringPlay.cs
new file mode 100644
index 0000000..e298cd7
--- /dev/null
+++ b/Assets/Cinemachine/Base/Editor/Utility/SaveDuringPlay.cs
@@ -0,0 +1,529 @@
+using System;
+using System.Collections.Generic;
+using System.Reflection;
+using UnityEditor;
+using UnityEngine;
+
+namespace SaveDuringPlay
+{
+ /// <summary>A collection of tools for finding objects</summary>
+ public static class ObjectTreeUtil
+ {
+ /// <summary>
+ /// Get the full name of an object, travelling up the transform parents to the root.
+ /// </summary>
+ public static string GetFullName(GameObject current)
+ {
+ if (current == null)
+ return "";
+ if (current.transform.parent == null)
+ return "/" + current.name;
+ return GetFullName(current.transform.parent.gameObject) + "/" + current.name;
+ }
+
+ /// <summary>
+ /// Will find the named object, active or inactive, from the full path.
+ /// </summary>
+ public static GameObject FindObjectFromFullName(string fullName, GameObject[] roots)
+ {
+ if (fullName == null || fullName.Length == 0 || roots == null)
+ return null;
+
+ string[] path = fullName.Split('/');
+ if (path.Length < 2) // skip leading '/'
+ return null;
+
+ Transform root = null;
+ for (int i = 0; root == null && i < roots.Length; ++i)
+ if (roots[i].name == path[1])
+ root = roots[i].transform;
+
+ if (root == null)
+ return null;
+
+ for (int i = 2; i < path.Length; ++i) // skip root
+ {
+ bool found = false;
+ for (int c = 0; c < root.childCount; ++c)
+ {
+ Transform child = root.GetChild(c);
+ if (child.name == path[i])
+ {
+ found = true;
+ root = child;
+ break;
+ }
+ }
+ if (!found)
+ return null;
+ }
+ return root.gameObject;
+ }
+
+ /// <summary>Finds all the root objects in a scene, active or not</summary>
+ public static GameObject[] FindAllRootObjectsInScene()
+ {
+ return UnityEngine.SceneManagement.SceneManager.GetActiveScene().GetRootGameObjects();
+ }
+
+
+ /// <summary>
+ /// This finds all the behaviours in scene, active or inactive, excluding prefabs
+ /// </summary>
+ public static T[] FindAllBehavioursInScene<T>() where T : MonoBehaviour
+ {
+ List<T> objectsInScene = new List<T>();
+ foreach (T b in Resources.FindObjectsOfTypeAll<T>())
+ {
+ GameObject go = b.gameObject;
+ if (go.hideFlags == HideFlags.NotEditable || go.hideFlags == HideFlags.HideAndDontSave)
+ continue;
+ if (EditorUtility.IsPersistent(go.transform.root.gameObject))
+ continue;
+ objectsInScene.Add(b);
+ }
+ return objectsInScene.ToArray();
+ }
+ }
+
+ class GameObjectFieldScanner
+ {
+ /// <summary>
+ /// Called for each leaf field. Return value should be true if action was taken.
+ /// It will be propagated back to the caller.
+ /// </summary>
+ public OnLeafFieldDelegate OnLeafField;
+ public delegate bool OnLeafFieldDelegate(string fullName, Type type, ref object value);
+
+ /// <summary>
+ /// Called for each field node, if and only if OnLeafField() for it or one
+ /// of its leaves returned true.
+ /// </summary>
+ public OnFieldValueChangedDelegate OnFieldValueChanged;
+ public delegate bool OnFieldValueChangedDelegate(
+ string fullName, FieldInfo fieldInfo, object fieldOwner, object value);
+
+ /// <summary>
+ /// Called for each field, to test whether to proceed with scanning it. Return true to scan.
+ /// </summary>
+ public FilterFieldDelegate FilterField;
+ public delegate bool FilterFieldDelegate(string fullName, FieldInfo fieldInfo);
+
+ /// <summary>
+ /// Which fields will be scanned
+ /// </summary>
+ public BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Instance;
+
+ bool ScanFields(string fullName, Type type, ref object obj)
+ {
+ bool doneSomething = false;
+
+ // Check if it's a complex type
+ bool isLeaf = true;
+ if (obj != null
+ && !type.IsSubclassOf(typeof(Component))
+ && !type.IsSubclassOf(typeof(GameObject)))
+ {
+ // Is it an array?
+ if (type.IsArray)
+ {
+ isLeaf = false;
+ Array array = obj as Array;
+ object arrayLength = array.Length;
+ if (OnLeafField != null && OnLeafField(
+ fullName + ".Length", arrayLength.GetType(), ref arrayLength))
+ {
+ Array newArray = Array.CreateInstance(
+ array.GetType().GetElementType(), Convert.ToInt32(arrayLength));
+ Array.Copy(array, 0, newArray, 0, Math.Min(array.Length, newArray.Length));
+ array = newArray;
+ doneSomething = true;
+ }
+ for (int i = 0; i < array.Length; ++i)
+ {
+ object element = array.GetValue(i);
+ if (ScanFields(fullName + "[" + i + "]", array.GetType().GetElementType(), ref element))
+ {
+ array.SetValue(element, i);
+ doneSomething = true;
+ }
+ }
+ if (doneSomething)
+ obj = array;
+ }
+ else
+ {
+ // Check if it's a complex type
+ FieldInfo[] fields = obj.GetType().GetFields(bindingFlags);
+ if (fields.Length > 0)
+ {
+ isLeaf = false;
+ for (int i = 0; i < fields.Length; ++i)
+ {
+ string name = fullName + "." + fields[i].Name;
+ if (FilterField == null || FilterField(name, fields[i]))
+ {
+ object fieldValue = fields[i].GetValue(obj);
+ if (ScanFields(name, fields[i].FieldType, ref fieldValue))
+ {
+ doneSomething = true;
+ if (OnFieldValueChanged != null)
+ OnFieldValueChanged(name, fields[i], obj, fieldValue);
+ }
+ }
+ }
+ }
+ }
+ }
+ // If it's a leaf field then call the leaf handler
+ if (isLeaf && OnLeafField != null)
+ if (OnLeafField(fullName, type, ref obj))
+ doneSomething = true;
+
+ return doneSomething;
+ }
+
+ public bool ScanFields(string fullName, MonoBehaviour b)
+ {
+ bool doneSomething = false;
+ FieldInfo[] fields = b.GetType().GetFields(bindingFlags);
+ if (fields.Length > 0)
+ {
+ for (int i = 0; i < fields.Length; ++i)
+ {
+ string name = fullName + "." + fields[i].Name;
+ if (FilterField == null || FilterField(name, fields[i]))
+ {
+ object fieldValue = fields[i].GetValue(b);
+ if (ScanFields(name, fields[i].FieldType, ref fieldValue))
+ doneSomething = true;
+
+ // If leaf action was taken, propagate it up to the parent node
+ if (doneSomething && OnFieldValueChanged != null)
+ OnFieldValueChanged(fullName, fields[i], b, fieldValue);
+ }
+ }
+ }
+ return doneSomething;
+ }
+
+ /// <summary>
+ /// Recursively scan the MonoBehaviours of a GameObject and its children.
+ /// For each leaf field found, call the OnFieldValue delegate.
+ /// </summary>
+ public bool ScanFields(GameObject go, string prefix = null)
+ {
+ bool doneSomething = false;
+ if (prefix == null)
+ prefix = "";
+ else if (prefix.Length > 0)
+ prefix += ".";
+
+ MonoBehaviour[] components = go.GetComponents<MonoBehaviour>();
+ for (int i = 0; i < components.Length; ++i)
+ {
+ MonoBehaviour c = components[i];
+ if (c != null && ScanFields(prefix + c.GetType().FullName + i, c))
+ doneSomething = true;
+ }
+ return doneSomething;
+ }
+ };
+
+
+ /// <summary>
+ /// Using reflection, this class scans a GameObject (and optionally its children)
+ /// and records all the field settings. This only works for "nice" field settings
+ /// within MonoBehaviours. Changes to the behaviour stack made between saving
+ /// and restoring will fool this class.
+ /// </summary>
+ class ObjectStateSaver
+ {
+ string mObjectFullPath;
+
+ Dictionary<string, string> mValues = new Dictionary<string, string>();
+
+ /// <summary>
+ /// Recursively collect all the field values in the MonoBehaviours
+ /// owned by this object and its descendants. The values are stored
+ /// in an internal dictionary.
+ /// </summary>
+ public void CollectFieldValues(GameObject go)
+ {
+ mObjectFullPath = ObjectTreeUtil.GetFullName(go);
+ GameObjectFieldScanner scanner = new GameObjectFieldScanner();
+ scanner.FilterField = FilterField;
+ scanner.OnLeafField = (string fullName, Type type, ref object value) =>
+ {
+ // Save the value in the dictionary
+ mValues[fullName] = StringFromLeafObject(value);
+ //Debug.Log(mObjectFullPath + "." + fullName + " = " + mValues[fullName]);
+ return false;
+ };
+ scanner.ScanFields(go);
+ }
+
+ public GameObject FindSavedGameObject(GameObject[] roots)
+ {
+ return ObjectTreeUtil.FindObjectFromFullName(mObjectFullPath, roots);
+ }
+ public string ObjetFullPath { get { return mObjectFullPath; } }
+
+ /// <summary>
+ /// Recursively scan the MonoBehaviours of a GameObject and its children.
+ /// For each field found, look up its value in the internal dictionary.
+ /// If it's present and its value in the dictionary differs from the actual
+ /// value in the game object, Set the GameObject's value using the value
+ /// recorded in the dictionary.
+ /// </summary>
+ public bool PutFieldValues(GameObject go, GameObject[] roots)
+ {
+ GameObjectFieldScanner scanner = new GameObjectFieldScanner();
+ scanner.FilterField = FilterField;
+ scanner.OnLeafField = (string fullName, Type type, ref object value) =>
+ {
+ // Lookup the value in the dictionary
+ string savedValue;
+ if (mValues.TryGetValue(fullName, out savedValue)
+ && StringFromLeafObject(value) != savedValue)
+ {
+ //Debug.Log(mObjectFullPath + "." + fullName + " = " + mValues[fullName]);
+ value = LeafObjectFromString(type, mValues[fullName].Trim(), roots);
+ return true; // changed
+ }
+ return false;
+ };
+ scanner.OnFieldValueChanged = (fullName, fieldInfo, fieldOwner, value) =>
+ {
+ fieldInfo.SetValue(fieldOwner, value);
+ return true;
+ };
+ return scanner.ScanFields(go);
+ }
+
+ /// Ignore fields marked with the [NoSaveDuringPlay] attribute
+ bool FilterField(string fullName, FieldInfo fieldInfo)
+ {
+ var attrs = fieldInfo.GetCustomAttributes(false);
+ foreach (var attr in attrs)
+ if (attr.GetType().Name.Contains("NoSaveDuringPlay"))
+ return false;
+ return true;
+ }
+
+ /// <summary>
+ /// Parse a string to generate an object.
+ /// Only very limited primitive object types are supported.
+ /// Enums, Vectors and most other structures are automatically supported,
+ /// because the reflection system breaks them down into their primitive components.
+ /// You can add more support here, as needed.
+ /// </summary>
+ static object LeafObjectFromString(Type type, string value, GameObject[] roots)
+ {
+ if (type == typeof(Single))
+ return float.Parse(value);
+ if (type == typeof(Double))
+ return double.Parse(value);
+ if (type == typeof(Boolean))
+ return Boolean.Parse(value);
+ if (type == typeof(string))
+ return value;
+ if (type == typeof(Int32))
+ return Int32.Parse(value);
+ if (type == typeof(UInt32))
+ return UInt32.Parse(value);
+ if (type.IsSubclassOf(typeof(Component)))
+ {
+ // Try to find the named game object
+ GameObject go = ObjectTreeUtil.FindObjectFromFullName(value, roots);
+ return (go != null) ? go.GetComponent(type) : null;
+ }
+ if (type.IsSubclassOf(typeof(GameObject)))
+ {
+ // Try to find the named game object
+ return GameObject.Find(value);
+ }
+ return null;
+ }
+
+ static string StringFromLeafObject(object obj)
+ {
+ if (obj == null)
+ return string.Empty;
+
+ if (obj.GetType().IsSubclassOf(typeof(Component)))
+ {
+ Component c = (Component)obj;
+ if (c == null) // Component overrides the == operator, so we have to check
+ return string.Empty;
+ return ObjectTreeUtil.GetFullName(c.gameObject);
+ }
+ if (obj.GetType().IsSubclassOf(typeof(GameObject)))
+ {
+ GameObject go = (GameObject)obj;
+ if (go == null) // GameObject overrides the == operator, so we have to check
+ return string.Empty;
+ return ObjectTreeUtil.GetFullName(go);
+ }
+ return obj.ToString();
+ }
+ };
+
+
+ /// <summary>
+ /// For all registered object types, record their state when exiting Play Mode,
+ /// and restore that state to the objects in the scene. This is a very limited
+ /// implementation which has not been rigorously tested with many objects types.
+ /// It's quite possible that not everything will be saved.
+ ///
+ /// This class is expected to become obsolete when Unity implements this functionality
+ /// in a more general way.
+ ///
+ /// To use this class,
+ /// drop this script into your project, and add the [SaveDuringPlay] attribute to your class.
+ ///
+ /// Note: if you want some specific field in your class NOT to be saved during play,
+ /// add a property attribute whose class name contains the string "NoSaveDuringPlay"
+ /// and the field will not be saved.
+ /// </summary>
+ [InitializeOnLoad]
+ public class SaveDuringPlay
+ {
+ public static string kEnabledKey = "SaveDuringPlay_Enabled";
+ public static bool Enabled
+ {
+ get { return EditorPrefs.GetBool(kEnabledKey, false); }
+ set
+ {
+ if (value != Enabled)
+ {
+ EditorPrefs.SetBool(kEnabledKey, value);
+ }
+ }
+ }
+
+ static SaveDuringPlay()
+ {
+ // Install our callbacks
+#if UNITY_2017_2_OR_NEWER
+ EditorApplication.playModeStateChanged += OnPlayStateChanged;
+#else
+ EditorApplication.update += OnEditorUpdate;
+ EditorApplication.playmodeStateChanged += OnPlayStateChanged;
+#endif
+ }
+
+#if UNITY_2017_2_OR_NEWER
+ static void OnPlayStateChanged(PlayModeStateChange pmsc)
+ {
+ if (Enabled)
+ {
+ // If exiting playmode, collect the state of all interesting objects
+ if (pmsc == PlayModeStateChange.ExitingPlayMode)
+ SaveAllInterestingStates();
+ else if (pmsc == PlayModeStateChange.EnteredEditMode && sSavedStates != null)
+ RestoreAllInterestingStates();
+ }
+ }
+#else
+ static void OnPlayStateChanged()
+ {
+ // If exiting playmode, collect the state of all interesting objects
+ if (Enabled)
+ {
+ if (!EditorApplication.isPlayingOrWillChangePlaymode && EditorApplication.isPlaying)
+ SaveAllInterestingStates();
+ }
+ }
+
+ static float sWaitStartTime = 0;
+ static void OnEditorUpdate()
+ {
+ if (Enabled && sSavedStates != null && !Application.isPlaying)
+ {
+ // Wait a bit for things to settle before applying the saved state
+ const float WaitTime = 1f; // GML todo: is there a better way to do this?
+ float time = Time.realtimeSinceStartup;
+ if (sWaitStartTime == 0)
+ sWaitStartTime = time;
+ else if (time - sWaitStartTime > WaitTime)
+ {
+ RestoreAllInterestingStates();
+ sWaitStartTime = 0;
+ }
+ }
+ }
+#endif
+
+ /// <summary>
+ /// If you need to get notified before state is collected for hotsave, this is the place
+ /// </summary>
+ public static OnHotSaveDelegate OnHotSave;
+ public delegate void OnHotSaveDelegate();
+
+ /// Collect all relevant objects, active or not
+ static Transform[] FindInterestingObjects()
+ {
+ List<Transform> objects = new List<Transform>();
+ MonoBehaviour[] everything = ObjectTreeUtil.FindAllBehavioursInScene<MonoBehaviour>();
+ foreach (var b in everything)
+ {
+ var attrs = b.GetType().GetCustomAttributes(true);
+ foreach (var attr in attrs)
+ {
+ if (attr.GetType().Name.Contains("SaveDuringPlay"))
+ {
+ //Debug.Log("Found " + ObjectTreeUtil.GetFullName(b.gameObject) + " for hot-save");
+ objects.Add(b.transform);
+ break;
+ }
+ }
+ }
+ return objects.ToArray();
+ }
+
+ static List<ObjectStateSaver> sSavedStates = null;
+ static GameObject sSaveStatesGameObject;
+ static void SaveAllInterestingStates()
+ {
+ //Debug.Log("Exiting play mode: Saving state for all interesting objects");
+ if (OnHotSave != null)
+ OnHotSave();
+
+ sSavedStates = new List<ObjectStateSaver>();
+ Transform[] objects = FindInterestingObjects();
+ foreach (Transform obj in objects)
+ {
+ ObjectStateSaver saver = new ObjectStateSaver();
+ saver.CollectFieldValues(obj.gameObject);
+ sSavedStates.Add(saver);
+ }
+ if (sSavedStates.Count == 0)
+ sSavedStates = null;
+ }
+
+ static void RestoreAllInterestingStates()
+ {
+ //Debug.Log("Updating state for all interesting objects");
+ bool dirty = false;
+ GameObject[] roots = ObjectTreeUtil.FindAllRootObjectsInScene();
+ foreach (ObjectStateSaver saver in sSavedStates)
+ {
+ GameObject go = saver.FindSavedGameObject(roots);
+ if (go != null)
+ {
+ Undo.RegisterFullObjectHierarchyUndo(go, "SaveDuringPlay");
+ if (saver.PutFieldValues(go, roots))
+ {
+ //Debug.Log("SaveDuringPlay: updated settings of " + saver.ObjetFullPath);
+ EditorUtility.SetDirty(go);
+ dirty = true;
+ }
+ }
+ }
+ if (dirty)
+ UnityEditorInternal.InternalEditorUtility.RepaintAllViews();
+ sSavedStates = null;
+ }
+ }
+}
diff --git a/Assets/Cinemachine/Base/Editor/Utility/SaveDuringPlay.cs.meta b/Assets/Cinemachine/Base/Editor/Utility/SaveDuringPlay.cs.meta
new file mode 100644
index 0000000..6898566
--- /dev/null
+++ b/Assets/Cinemachine/Base/Editor/Utility/SaveDuringPlay.cs.meta
@@ -0,0 +1,12 @@
+fileFormatVersion: 2
+guid: 24ec24775a1b45e4ea81ac13002dee32
+timeCreated: 1485895820
+licenseType: Store
+MonoImporter:
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Assets/Cinemachine/Base/Editor/Utility/ScriptableObjectUtility.cs b/Assets/Cinemachine/Base/Editor/Utility/ScriptableObjectUtility.cs
new file mode 100644
index 0000000..88dac2c
--- /dev/null
+++ b/Assets/Cinemachine/Base/Editor/Utility/ScriptableObjectUtility.cs
@@ -0,0 +1,160 @@
+using UnityEngine;
+using UnityEditor;
+using System.IO;
+using System.Linq;
+using System;
+
+namespace Cinemachine.Editor
+{
+ public class ScriptableObjectUtility : ScriptableObject
+ {
+ public static string CinemachineInstallPath
+ {
+ get { return Path.GetFullPath(CinemachineInstallAssetPath); }
+ }
+
+ public static string CinemachineInstallAssetPath
+ {
+ get
+ {
+ ScriptableObject dummy = ScriptableObject.CreateInstance<ScriptableObjectUtility>();
+ string path = AssetDatabase.GetAssetPath(MonoScript.FromScriptableObject(dummy));
+ DestroyImmediate(dummy);
+ path = path.Substring(0, path.LastIndexOf("/Base"));
+ return path;
+ }
+ }
+
+ public static bool CinemachineIsPackage
+ {
+ get { return CinemachineInstallAssetPath.StartsWith("Packages"); }
+ }
+
+ public static bool AddDefineForAllBuildTargets(string k_Define)
+ {
+ bool added = false;
+ var targets = Enum.GetValues(typeof(BuildTargetGroup))
+ .Cast<BuildTargetGroup>()
+ .Where(x => x != BuildTargetGroup.Unknown)
+ .Where(x => !BuildTargetIsObsolete(x));
+
+ foreach (var target in targets)
+ {
+ var defines = PlayerSettings.GetScriptingDefineSymbolsForGroup(target).Trim();
+
+ var list = defines.Split(';', ' ')
+ .Where(x => !string.IsNullOrEmpty(x))
+ .ToList();
+
+ if (!list.Contains(k_Define))
+ {
+ list.Add(k_Define);
+ defines = list.Aggregate((a, b) => a + ";" + b);
+
+ PlayerSettings.SetScriptingDefineSymbolsForGroup(target, defines);
+ added = true;
+ }
+ }
+ return added;
+ }
+
+ static bool BuildTargetIsObsolete(BuildTargetGroup group)
+ {
+ var attrs = typeof(BuildTargetGroup)
+ .GetField(group.ToString())
+ .GetCustomAttributes(typeof(ObsoleteAttribute), false);
+
+ return attrs != null && attrs.Length > 0;
+ }
+
+ public static void Create<T>(bool prependFolderName = false, bool trimName = true) where T : ScriptableObject
+ {
+ string className = typeof(T).Name;
+ string assetName = className;
+ string folder = GetSelectedAssetFolder();
+
+ if (trimName)
+ {
+ string[] standardNames = new string[] { "Asset", "Attributes", "Container" };
+ foreach (string standardName in standardNames)
+ {
+ assetName = assetName.Replace(standardName, "");
+ }
+ }
+
+ if (prependFolderName)
+ {
+ string folderName = Path.GetFileName(folder);
+ assetName = (string.IsNullOrEmpty(assetName) ? folderName : string.Format("{0}_{1}", folderName, assetName));
+ }
+
+ Create(className, assetName, folder);
+ }
+
+ public static T CreateAt<T>(string assetPath) where T : ScriptableObject
+ {
+ T asset = ScriptableObject.CreateInstance<T>();
+ if (asset == null)
+ {
+ Debug.LogError("failed to create instance of " + typeof(T).Name);
+ return null;
+ }
+
+ AssetDatabase.CreateAsset(asset, assetPath);
+
+ return asset;
+ }
+
+ private static ScriptableObject Create(string className, string assetName, string folder)
+ {
+ ScriptableObject asset = ScriptableObject.CreateInstance(className);
+ if (asset == null)
+ {
+ Debug.LogError("failed to create instance of " + className);
+ return null;
+ }
+
+ asset.name = assetName ?? className;
+
+ string assetPath = GetUnusedAssetPath(folder, asset.name);
+ AssetDatabase.CreateAsset(asset, assetPath);
+
+ return asset;
+ }
+
+ private static string GetSelectedAssetFolder()
+ {
+ if ((Selection.activeObject != null) && AssetDatabase.Contains(Selection.activeObject))
+ {
+ string assetPath = AssetDatabase.GetAssetPath(Selection.activeObject);
+ string assetPathAbsolute = string.Format("{0}/{1}", Path.GetDirectoryName(Application.dataPath), assetPath);
+
+ if (Directory.Exists(assetPathAbsolute))
+ {
+ return assetPath;
+ }
+ else
+ {
+ return Path.GetDirectoryName(assetPath);
+ }
+ }
+
+ return "Assets";
+ }
+
+ private static string GetUnusedAssetPath(string folder, string assetName)
+ {
+ for (int n = 0; n < 9999; n++)
+ {
+ string assetPath = string.Format("{0}/{1}{2}.asset", folder, assetName, (n == 0 ? "" : n.ToString()));
+ string existingGUID = AssetDatabase.AssetPathToGUID(assetPath);
+ if (string.IsNullOrEmpty(existingGUID))
+ {
+ return assetPath;
+ }
+ }
+
+ return null;
+ }
+ }
+}
diff --git a/Assets/Cinemachine/Base/Editor/Utility/ScriptableObjectUtility.cs.meta b/Assets/Cinemachine/Base/Editor/Utility/ScriptableObjectUtility.cs.meta
new file mode 100644
index 0000000..67584e7
--- /dev/null
+++ b/Assets/Cinemachine/Base/Editor/Utility/ScriptableObjectUtility.cs.meta
@@ -0,0 +1,12 @@
+fileFormatVersion: 2
+guid: ba59c38a116ff2f4fb69f825ba0da3bc
+timeCreated: 1481654957
+licenseType: Store
+MonoImporter:
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Assets/Cinemachine/Base/Editor/Utility/SerializedPropertyHelper.cs b/Assets/Cinemachine/Base/Editor/Utility/SerializedPropertyHelper.cs
new file mode 100644
index 0000000..e93253e
--- /dev/null
+++ b/Assets/Cinemachine/Base/Editor/Utility/SerializedPropertyHelper.cs
@@ -0,0 +1,59 @@
+using System;
+using System.Linq.Expressions;
+using UnityEditor;
+
+namespace Cinemachine.Editor
+{
+ public static class SerializedPropertyHelper
+ {
+ /// This is a way to get a field name string in such a manner that the compiler will
+ /// generate errors for invalid fields. Much better than directly using strings.
+ /// Usage: instead of
+ /// <example>
+ /// "m_MyField";
+ /// </example>
+ /// do this:
+ /// <example>
+ /// MyClass myclass = null;
+ /// SerializedPropertyHelper.PropertyName( () => myClass.m_MyField);
+ /// </example>
+ public static string PropertyName(Expression<Func<object>> exp)
+ {
+ var body = exp.Body as MemberExpression;
+ if (body == null)
+ {
+ var ubody = (UnaryExpression)exp.Body;
+ body = ubody.Operand as MemberExpression;
+ }
+ return body.Member.Name;
+ }
+
+ /// Usage: instead of
+ /// <example>
+ /// mySerializedObject.FindProperty("m_MyField");
+ /// </example>
+ /// do this:
+ /// <example>
+ /// MyClass myclass = null;
+ /// mySerializedObject.FindProperty( () => myClass.m_MyField);
+ /// </example>
+ public static SerializedProperty FindProperty(this SerializedObject obj, Expression<Func<object>> exp)
+ {
+ return obj.FindProperty(PropertyName(exp));
+ }
+
+ /// Usage: instead of
+ /// <example>
+ /// mySerializedProperty.FindPropertyRelative("m_MyField");
+ /// </example>
+ /// do this:
+ /// <example>
+ /// MyClass myclass = null;
+ /// mySerializedProperty.FindPropertyRelative( () => myClass.m_MyField);
+ /// </example>
+ public static SerializedProperty FindPropertyRelative(this SerializedProperty obj, Expression<Func<object>> exp)
+ {
+ return obj.FindPropertyRelative(PropertyName(exp));
+ }
+ }
+}
diff --git a/Assets/Cinemachine/Base/Editor/Utility/SerializedPropertyHelper.cs.meta b/Assets/Cinemachine/Base/Editor/Utility/SerializedPropertyHelper.cs.meta
new file mode 100644
index 0000000..4dd5d65
--- /dev/null
+++ b/Assets/Cinemachine/Base/Editor/Utility/SerializedPropertyHelper.cs.meta
@@ -0,0 +1,12 @@
+fileFormatVersion: 2
+guid: a60d9407e2bb20e4ea00281b1e33eae7
+timeCreated: 1488400542
+licenseType: Store
+MonoImporter:
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant: