Exemplo n.º 1
0
        /// <summary>
        /// Attempts to extract the name of serialized key for the given property
        /// modification.
        /// </summary>
        /// <param name="obj">
        /// The object that that modification is applied to.
        /// </param>
        /// <param name="mod">The modification.</param>
        /// <param name="keyName">
        /// An output parameter containing the name of the key that the
        /// modification maps to.
        /// </param>
        /// <returns>True if the key was found, false otherwise.</returns>
        private static bool TryExtractPropertyName(
            ISerializedObject obj,
            PropertyModification mod,
            out string keyName)
        {
            //-
            // We want to extract 2 from _serializedStateValues.Array.data[2]
            // We could probably use a regular expression, but this is fine for now
            if (mod.propertyPath.StartsWith("_serializedStateValues.Array.data["))
            {
                string front = mod.propertyPath.Remove(0, "_serializedStateValues.Array.data".Length + 1);
                string num   = front.Substring(0, front.Length - 1);

                int index;
                if (int.TryParse(num, out index) &&
                    index >= 0 && index < obj.SerializedStateKeys.Count)
                {
                    keyName = obj.SerializedStateKeys[index];
                    return(true);
                }
            }

            keyName = string.Empty;
            return(false);
        }
Exemplo n.º 2
0
 /// <summary>
 /// Used internally to notify us that an object has been serialized. We update some metadata stored on the object
 /// upon each serialization so we can detect when prefab modifications are applied.
 /// </summary>
 public static void MarkSerialized(ISerializedObject obj)
 {
     if (fiUtility.IsEditor)
     {
         _deserializedObjects[obj] = new SerializedObjectSnapshot(obj);
     }
 }
Exemplo n.º 3
0
        private static void ChangeStates(UnityObject target, MethodInfo restoreState, MethodInfo saveState)
        {
            object result = restoreState.Invoke(null, new object[] { target });

            if ((bool)result == false)
            {
                Debug.LogWarning("Skipping " + target + " -- unable to successfuly deserialize", target);
                return;
            }

            ISerializedObject serializedObj = (ISerializedObject)target;
            var savedKeys   = new List <string>(serializedObj.SerializedStateKeys);
            var savedValues = new List <string>(serializedObj.SerializedStateValues);
            var savedRefs   = new List <UnityObject>(serializedObj.SerializedObjectReferences);

            result = saveState.Invoke(null, new object[] { target });
            if ((bool)result == false)
            {
                Debug.LogWarning("Skipping " + target + " -- unable to successfuly serialize", target);

                serializedObj.SerializedStateKeys        = savedKeys;
                serializedObj.SerializedStateValues      = savedValues;
                serializedObj.SerializedObjectReferences = savedRefs;

                return;
            }

            Debug.Log("Successfully migrated " + target, target);
            EditorUtility.SetDirty(target);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Attempts to serialize the given object. Serialization will only occur if the object is
        /// dirty. After being serialized, the object is no longer dirty.
        /// </summary>
        public static void SubmitSerializeRequest(ISerializedObject obj)
        {
            lock (typeof(fiEditorSerializationManager)) {
                bool isDirty = _dirty.Contains(obj);

                // Serialization is disabled
                if (DisableAutomaticSerialization)
                {
                    return;
                }

                // The given object is the current inspected object and we havne't marked it as
                // dirty. There is no need to serialize it. This results in a large perf gain, as
                // Unity will send serialize requests continously to the inspected object.
                if (!isDirty && fiLateBindings.Selection.activeObject == GetGameObjectOrScriptableObjectFrom(obj))
                {
                    return;
                }

                // The object is dirty or we have deserialized it. A serialize request has been submitted
                // so we should actually service it.
                if (isDirty || _deserializedObjects.ContainsKey(obj) || obj is ISerializationAlwaysDirtyTag)
                {
                    DoSerialize(obj);
                    _dirty.Remove(obj);
                }
            }
        }
        private static bool SaveStateForProperty(ISerializedObject obj, InspectedProperty property, BaseSerializer serializer, ISerializationOperator serializationOperator, out string serializedValue, ref bool success)
        {
            object currentValue = property.Read(obj);

            try {
                if (currentValue == null)
                {
                    serializedValue = null;
                }
                else
                {
                    serializedValue = serializer.Serialize(property.MemberInfo, currentValue, serializationOperator);
                }
                return(true);
            }
            catch (Exception e) {
                success         = false;
                serializedValue = null;

                Debug.LogError("Exception caught when serializing property <" +
                               property.Name + "> in <" + obj + "> with value " + currentValue + "\n" +
                               e);
                return(false);
            }
        }
Exemplo n.º 6
0
        private static void DrawSerializedState(ISerializedObject behavior)
        {
            if (_editorShowSerializedState)
            {
                var flags = ReorderableListFlags.HideAddButton | ReorderableListFlags.DisableReordering;

                EditorGUILayout.HelpBox("The following is raw serialization data. Only change it " +
                                        "if you know what you're doing or you could corrupt your object!",
                                        MessageType.Warning);

                ReorderableListGUI.Title("Serialized Keys");
                ReorderableListGUI.ListField(new ListAdaptor <string>(
                                                 behavior.SerializedStateKeys ?? new List <string>(),
                                                 DrawItem, GetItemHeight, SerializedStateMetadata), flags);

                ReorderableListGUI.Title("Serialized Values");
                ReorderableListGUI.ListField(new ListAdaptor <string>(
                                                 behavior.SerializedStateValues ?? new List <string>(),
                                                 DrawItem, GetItemHeight, SerializedStateMetadata), flags);

                ReorderableListGUI.Title("Serialized Object References");
                ReorderableListGUI.ListField(new ListAdaptor <UnityObject>(
                                                 behavior.SerializedObjectReferences ?? new List <UnityObject>(),
                                                 DrawItem, GetItemHeight, SerializedStateMetadata), flags);
            }
        }
        public IAdvancedScript DeSerialize(ISerializedObject <IAdvancedScript> serialized, ISerializer serializer, object deserializationContext)
        {
            if (serialized is not SerializedAdvancedScript serializedAdvancedScript)
            {
                throw new ArgumentException("AdvancedScriptSerializer can only deserialize objects of type SerializedAdvancedScript");
            }

            IAdvancedScript output = _factory.GetImplementation <IAdvancedScript>();

            output.Name.Value    = serializedAdvancedScript.Name;
            output.IsBeingEdited = true;

            foreach (var kvp in serializedAdvancedScript.Inputs)
            {
                output.Editor.Inputs.Add(kvp.Key, serializer.TryDeserializeObject(kvp.Value, null));
            }
            output.UpdateInputs();

            foreach (var node in serializedAdvancedScript.Nodes)
            {
                output.Editor.AddNode(serializer.Deserialize(node, output));
            }

            foreach (ISerializedObject <INodeConnection> connection in serializedAdvancedScript.Connections)
            {
                serializer.Deserialize(connection, output.Editor);
            }

            output.IsBeingEdited = false;

            return(output);
        }
 private static int GetHash(ISerializedObject obj)
 {
     int num = 27;
     foreach (UnityEngine.Object current in obj.SerializedObjectReferences)
     {
         if (current != null)
         {
             bool flag;
             long id = ObjectModificationDetector._unityObjectIds.GetId(current, out flag);
             num = 13 * num + (int)id;
         }
     }
     foreach (string current2 in obj.SerializedStateKeys)
     {
         num = 13 * num + current2.GetHashCode();
     }
     foreach (string current3 in obj.SerializedStateValues)
     {
         if (current3 != null)
         {
             num = 13 * num + current3.GetHashCode();
         }
     }
     return num;
 }
Exemplo n.º 9
0
        private static void HandleReset(ISerializedObject obj)
        {
            // We don't want to send a reset notification for new objects which have no data. If we've already
            // seen an object and it has no data, then it was certainly reset.
            if (s_seen.Add(obj))
            {
                return;
            }

            // All serialized data is wiped out, but we have already seen/serialized this object. Very likely it got
            // reset.
            if (IsNullOrEmpty(obj.SerializedObjectReferences) &&
                IsNullOrEmpty(obj.SerializedStateKeys) &&
                IsNullOrEmpty(obj.SerializedStateValues))
            {
                fiLog.Log(typeof(fiSerializationManager), "Reseting object of type {0}", obj.GetType());

                // Note: we do not clear out the keys; if we did, then we would not actually deserialize "null" onto them
                // Note: we call SaveState() so we can fetch the keys we need to deserialize
                obj.SaveState();
                for (int i = 0; i < obj.SerializedStateValues.Count; ++i)
                {
                    obj.SerializedStateValues[i] = null;
                }
                obj.RestoreState();

                // TODO: Does Reset get invoked off the Unity thread? Will it get invoked twice,
                //       once by Unity and once by Full Inspector?
                fiRuntimeReflectionUtility.InvokeMethod(obj.GetType(), "Reset", obj, null);

                obj.SaveState();
            }
        }
Exemplo n.º 10
0
        private static void CheckForReset(ISerializedObject obj)
        {
            SerializedObjectSnapshot originalData = null;

            if (_deserializedObjects.TryGetValue(obj, out originalData))
            {
                if (originalData.IsEmpty)
                {
                    return;
                }

                if (obj.SerializedStateKeys == null || obj.SerializedStateKeys.Count == 0 ||
                    obj.SerializedStateValues == null || obj.SerializedStateValues.Count == 0)
                {
                    // Note: we do not clear out the keys; if we did, then we would not actually deserialize "null" onto them
                    // Note: we call SaveState() so we can fetch the keys we need to deserialize
                    obj.SaveState();
                    obj.SerializedStateValues.Clear();
                    for (int i = 0; i < obj.SerializedStateKeys.Count; ++i)
                    {
                        obj.SerializedStateValues.Add(null);
                    }
                    obj.RestoreState();

                    fiRuntimeReflectionUtility.InvokeMethod(obj.GetType(), "Reset", obj, null);

                    obj.SaveState();
                    _deserializedObjects[obj] = new SerializedObjectSnapshot(obj);
                }
            }
        }
Exemplo n.º 11
0
 public static bool WasModified(ISerializedObject obj)
 {
     bool flag;
     long id = ObjectModificationDetector._ids.GetId(obj, out flag);
     int num;
     return !ObjectModificationDetector._serializedStates.TryGetValue(id, out num) || num != ObjectModificationDetector.GetHash(obj);
 }
 public void RestoreSnapshot(ISerializedObject target)
 {
     target.SerializedStateKeys        = new List <string>(_keys);
     target.SerializedStateValues      = new List <string>(_values);
     target.SerializedObjectReferences = new List <UnityObject>(_objectReferences);
     target.RestoreState();
 }
        private static void CheckForReset(ISerializedObject obj)
        {
            // We don't want to send a reset notification for new objects which have no data. If we've already
            // seen an object and it has no data, then it was certainly reset.
            if (s_seen.Add(obj))
            {
                return;
            }

            if (IsNullOrEmpty(obj.SerializedObjectReferences) && IsNullOrEmpty(obj.SerializedStateKeys) && IsNullOrEmpty(obj.SerializedStateValues))
            {
                // Note: we do not clear out the keys; if we did, then we would not actually deserialize "null" onto them
                // Note: we call SaveState() so we can fetch the keys we need to deserialize
                obj.SaveState();
                for (int i = 0; i < obj.SerializedStateValues.Count; ++i)
                {
                    obj.SerializedStateValues[i] = null;
                }
                obj.RestoreState();

                fiRuntimeReflectionUtility.InvokeMethod(obj.GetType(), "Reset", obj, null);

                obj.SaveState();
            }
        }
Exemplo n.º 14
0
 /// <summary>
 /// Fetches the associated GameObject/ScriptableObject from the given serialized object.
 /// </summary>
 private static UnityObject GetGameObjectOrScriptableObjectFrom(ISerializedObject obj)
 {
     if (obj is MonoBehaviour)
     {
         return(((MonoBehaviour)obj).gameObject);
     }
     return((UnityObject)obj);
 }
Exemplo n.º 15
0
 static DataResult ToXmlResult(ISerializedObject r)
 {
     return(new DataResult(r, (response, sw) =>
     {
         response.ContentType = "text/xml";
         return new XmlISerializedObjectWriter(new XmlTextWriter(sw));
     }));
 }
Exemplo n.º 16
0
 static DataResult ToJsonResult(ISerializedObject r)
 {
     return(new DataResult(r, (response, sw) =>
     {
         response.ContentType = "application/json";
         return new JsonISerializedObjectWriter(sw);
     }));
 }
 public static ISerializedObject <T> Convert <T>(this IConverter converter, ISerializedObject original)
 {
     if (original.ContentType == typeof(T))
     {
         return((ISerializedObject <T>)original);
     }
     return(new SimpleSerializedObject <T>(converter.Convert <T>(original.Data, original.ContentType), original.Type));
 }
Exemplo n.º 18
0
        public static void RunDeserializations()
        {
            // We never run deserializations outside of the editor
            if (fiUtility.IsEditor == false)
            {
                return;
            }

            // Serialization is disabled
            if (DisableAutomaticSerialization)
            {
                return;
            }

            // Do not deserialize in the middle of a level load that might be running on another thread
            // (asynchronous) which can lead to a race condition causing the following assert:
            // ms_IDToPointer->find (obj->GetInstanceID ()) == ms_IDToPointer->end ()
            //
            // Very strange that the load is happening on another thread since RunDeserializations only
            // gets invoked from EditorApplication.update and EditorWindow.OnGUI.
            //
            // This method will get called again at a later point so there is no worries that we haven't
            // finished doing the deserializations.
            if (fiLateBindings.EditorApplication.isPlaying && Application.isLoadingLevel)
            {
                return;
            }

            while (_toDeserialize.Count > 0)
            {
                ISerializedObject item = _toDeserialize.Dequeue();

                // If we're in play-mode, then we don't want to deserialize anything as that can wipe
                // user-data. We cannot do this in SubmitDeserializeRequest because
                // EditorApplication.isPlaying can only be called from the main thread. However,
                // we *do* want to restore prefabs and general disk-based resources which will not have
                // Awake called.
                if (fiLateBindings.EditorApplication.isPlaying)
                {
                    // note: We do a null check against unityObj to also check for destroyed objects,
                    //       which we don't need to bother restoring. Doing a null check against an
                    //       ISerializedObject instance will *not* call the correct == method, so
                    //       we need to be explicit about calling it against UnityObject.
                    var unityObj = item as UnityObject;

                    if (unityObj == null ||
                        fiLateBindings.PrefabUtility.IsPrefab(unityObj) == false)
                    {
                        continue;
                    }
                }

                CheckForReset(item);

                item.RestoreState();
                _deserializedObjects[item] = new SerializedObjectSnapshot(item);
            }
        }
Exemplo n.º 19
0
 static DataResult ToCsvResult(ISerializedObject r, string downloadFileName = "data.csv")
 {
     return(new DataResult(r, (response, sw) =>
     {
         response.ContentType = "application/csv";
         response.AddHeader("Content-Disposition", "attachment;filename=" + downloadFileName);
         return new CSVISerializedObjectWriter(sw);
     }));
 }
        public KeyboardKey DeSerialize(ISerializedObject <KeyboardKey> serialized, ISerializer serializer, object deserializationContext)
        {
            if (serialized is not SerializedKeyboardKey serializedKeyboardKey)
            {
                throw new ArgumentException("Can only deserialize objects of type SerializedKeyboardKey");
            }

            return(new KeyboardKey(serializedKeyboardKey.VirtualKey, serializedKeyboardKey.Modifiers));
        }
Exemplo n.º 21
0
        static DataResult ToHTMLResult(ISerializedObject r)
        {
            return(new DataResult(r, (response, sw) =>
            {
                response.ContentType = "text/html";

                return new HTMLISerializedObjectWriter(sw);
            }));
        }
Exemplo n.º 22
0
        static public void ConstructorStructsCanBeDeserializedAsInterfaces()
        {
            ISerializedObject obj        = new TestSerializedStruct(5);
            string            serialized = Serializer.Write(obj, OutputOptions.None, Serializer.Format.JSON);
            ISerializedObject readTest   = Serializer.Read <ISerializedObject>(serialized);

            Assert.IsInstanceOf(typeof(TestSerializedStruct), readTest);
            Assert.AreEqual(5, ((TestSerializedStruct)readTest).Value);
        }
Exemplo n.º 23
0
        private bool GetDataAction(ISerializedObject serializer, ref byte[] data)
        {
            var buffer = serializer.GetBuffer();

            if (buffer != null)
            {
                data = CopyBuffer(buffer);
                return(true);
            }
            throw new Exception("Unable to retrieve data from serialized object!");
        }
Exemplo n.º 24
0
        /// <summary>
        /// Common logic for Awake() or OnEnable() methods inside of behaviors.
        /// </summary>
        public static void OnUnityObjectAwake <TSerializer>(ISerializedObject obj) where TSerializer : BaseSerializer
        {
            // No need to deserialize (possibly deserialized via OnUnityObjectDeserialize)
            if (obj.IsRestored)
            {
                return;
            }

            // Otherwise do a regular deserialization
            DoDeserialize(obj);
        }
        private static void SkipCloningValues(ISerializedObject obj)
        {
            lock (_skipSerializationQueue) {
                if (_skipSerializationQueue.ContainsKey(obj.SharedStateGuid))
                {
                    return;
                }

                _skipSerializationQueue[obj.SharedStateGuid] = obj;
            }
        }
Exemplo n.º 26
0
        public void ReturnJson(ISerializedObject item)
        {
            using (var sw = new StringWriter())
            {
                using (var x = new JsonISerializedObjectWriter(sw))
                {
                    item.ToWriter(x);
                }

                WriteJsonString(sw.ToString());
            }
        }
Exemplo n.º 27
0
        private bool Read_Object <T>(ref T ioObject) where T : ISerializedObject
        {
            string typeName    = null;
            bool   typeSuccess = DoRead(TYPE_KEY, ref typeName, null, FieldOptions.PreferAttribute,
                                        Read_String_Cached ?? (Read_String_Cached = Read_String));

            if (!typeSuccess)
            {
                AddErrorMessage("Unable to read object type info");
            }

            Type objectType = typeof(T);

            if (!string.IsNullOrEmpty(typeName))
            {
                objectType = TypeUtility.NameToType(typeName);
            }

            if (ioObject == null || ioObject.GetType().TypeHandle.Value != objectType.TypeHandle.Value)
            {
                ioObject = (T)TypeUtility.Instantiate(objectType, this);
            }

            ushort version        = 1;
            bool   versionSuccess = DoRead(VERSION_KEY, ref version, (ushort)1, FieldOptions.PreferAttribute, Read_UInt16_Cached ?? (Read_UInt16_Cached = Read_UInt16));

            if (!versionSuccess)
            {
                AddErrorMessage("Unable to read object version info");
            }

            ushort prevVersion = ObjectVersion;

            ObjectVersion = version;

            ISerializedCallbacks callback = ioObject as ISerializedCallbacks;

            if (callback != null)
            {
                PreSerialize(callback);
            }

            int prevErrorLength   = m_ErrorString.Length;
            ISerializedObject obj = ioObject;

            obj.Serialize(this);
            ioObject = (T)obj;

            ObjectVersion = prevVersion;
            return(typeSuccess && versionSuccess && (m_ErrorString.Length == prevErrorLength));
        }
Exemplo n.º 28
0
        private static void DoSerialize(ISerializedObject obj)
        {
            // If we have serialization disabled, then we *definitely* do not
            // want to do anything.
            // Note: We put this check here for code clarity / robustness
            //       purposes. If this proves to be a perf issue, it can be
            //       hoisted outside of the top-level loop which invokes this
            //       method.
            if (DisableAutomaticSerialization)
            {
                return;
            }

            bool forceSerialize = obj is UnityObject && DirtyForceSerialize.Contains((UnityObject)obj);

            if (forceSerialize)
            {
                DirtyForceSerialize.Remove((UnityObject)obj);
            }

            // Do not serialize objects which have been destroyed.
            if (obj is UnityObject && ((UnityObject)obj) == null)
            {
                return;
            }

            // If this object is currently being inspected then we don't want to
            // serialize it. This gives a big perf boost. Note that we *do* want
            // to serialize the object if we are entering play-mode or compiling
            // - otherwise a data loss will occur.
            if (forceSerialize == false && obj is UnityObject)
            {
                // If the serialized object request belongs to any of the items
                // in the selection, serialize it later. We have to use
                // s_cachedSelection because Selection.activeGameObject will
                // throw an exception if we are currently on a non-Unity thread.
                var toSerialize = (UnityObject)obj;
                for (int i = 0; i < s_cachedSelection.Length; ++i)
                {
                    if (ReferenceEquals(toSerialize, s_cachedSelection[i]))
                    {
                        s_inspectedObjectSerialization.RequestSerialization(toSerialize);
                        return;
                    }
                }
            }

            HandleReset(obj);
            obj.SaveState();
        }
Exemplo n.º 29
0
        /// <summary>
        /// Construct a new event entry from a published event message to enable storing the event or sending it to a remote
        /// location.
        /// <p>
        /// The given {@code serializer} will be used to serialize the payload and metadata in the given {@code eventMessage}.
        /// The type of the serialized data will be the same as the given {@code contentType}.
        /// </summary>
        /// <param name="eventMessage">The event message to convert to a serialized event entry</param>
        /// <param name="serializer">The serializer to convert the event</param>
        /// <param name="contentType">The data type of the payload and metadata after serialization</param>
        public AbstractEventEntry(
            IEventMessage <object> eventMessage,
            ISerializer serializer,
            Type contentType)
        {
            ISerializedObject <T> payload  = eventMessage.SerializePayload <T>(serializer, contentType);
            ISerializedObject <T> metaData = eventMessage.SerializeMetaData <T>(serializer, contentType);

            _eventIdentifier = eventMessage.GetIdentifier();
            _payloadType     = payload.Type() !.GetName();
            _payloadRevision = payload.Type() !.GetRevision();
            _payload         = payload.GetData();
            _metaData        = metaData.GetData();
            _timeStamp       = DateTimeUtils.FormatInstant(eventMessage.GetTimestamp() !);
        }
Exemplo n.º 30
0
 public void WriteIserializedObject(ISerializedObject value)
 {
     if (!_inValue)
     {
         value.ToWriter(this);
     }
     else
     {
         using (var sw = new StringWriter())
         {
             value.ToWriter(new HTMLISerializedObjectWriter(sw));
             WriteValue(sw.ToString());
         }
     }
     //value.ToWriter(new CSVISerializedObjectWriter(_writer));
 }
        private static void DoSerialize(ISerializedObject obj)
        {
            // If we have serialization disabled, then we *definitely* do not want to do anything.
            // Note: We put this check here for code clarity / robustness purposes. If this proves to be a
            //       perf issue, it can be hoisted outside of the top-level loop which invokes this method.
            if (DisableAutomaticSerialization)
            {
                return;
            }

            bool forceSerialize = obj is UnityObject && DirtyForceSerialize.Contains((UnityObject)obj);

            if (forceSerialize)
            {
                DirtyForceSerialize.Remove((UnityObject)obj);
            }

            // If this object is currently being inspected then we don't want to serialize it. This gives
            // a big perf boost. Note that we *do* want to serialize the object if we are entering play-mode
            // or compiling - otherwise a data loss will occur.
            if (forceSerialize == false &&
                obj is UnityObject &&
                fiLateBindings.EditorApplication.isCompilingOrChangingToPlayMode == false)
            {
                var toSerialize = (UnityObject)obj;
                if (toSerialize is Component)
                {
                    toSerialize = ((Component)toSerialize).gameObject;
                }

                var selected = fiLateBindings.Selection.activeObject;
                if (selected is Component)
                {
                    selected = ((Component)selected).gameObject;
                }

                if (ReferenceEquals(toSerialize, selected))
                {
                    return;
                }
            }

            CheckForReset(obj);
            obj.SaveState();
        }
Exemplo n.º 32
0
        /// <summary>
        /// Attempt to deserialize the given object. The deserialization will occur on the next
        /// call to RunDeserializations(). This does nothing if we are not an editor.
        /// </summary>
        public static void SubmitDeserializeRequest(ISerializedObject obj)
        {
            lock (typeof(fiEditorSerializationManager)) {
                if (fiUtility.IsEditor == false)
                {
                    return;
                }

                _toDeserialize.Enqueue(obj);

                /* NOTE: Disabled for now, possibly useful in the future.
                 * // If we're on the main thread, then we should try to do some deserializations.
                 * if (fiUtility.IsMainThread) {
                 *  RunDeserializations();
                 * }
                 */
            }
        }
        private static void DrawSerializedState(ISerializedObject behavior) {
            if (_editorShowSerializedState) {
                var flags = ReorderableListFlags.HideAddButton | ReorderableListFlags.DisableReordering;

                EditorGUILayout.HelpBox("The following is raw serialization data. Only change it " +
                    "if you know what you're doing or you could corrupt your object!",
                    MessageType.Warning);

                ReorderableListGUI.Title("Serialized Keys");
                ReorderableListGUI.ListField(new ListAdaptor<string>(
                    behavior.SerializedStateKeys, DrawItem, GetItemHeight, SerializedStateMetadata), flags);

                ReorderableListGUI.Title("Serialized Values");
                ReorderableListGUI.ListField(new ListAdaptor<string>(
                    behavior.SerializedStateValues, DrawItem, GetItemHeight, SerializedStateMetadata), flags);

                ReorderableListGUI.Title("Serialized Object References");
                ReorderableListGUI.ListField(new ListAdaptor<UnityObject>(
                    behavior.SerializedObjectReferences, DrawItem, GetItemHeight, SerializedStateMetadata), flags);
            }
        }
Exemplo n.º 34
0
        /// <summary>
        /// Attempts to extract the name of serialized key for the given property modification.
        /// </summary>
        /// <param name="obj">The object that that modification is applied to.</param>
        /// <param name="mod">The modification.</param>
        /// <param name="keyName">An output parameter containing the name of the key that the
        /// modification maps to.</param>
        /// <returns>True if the key was found, false otherwise.</returns>
        private static bool TryExtractPropertyName(ISerializedObject obj, PropertyModification mod,
            out string keyName) {

            //-
            // We want to extract 2 from _serializedStateValues.Array.data[2]
            // We could probably use a regular expression, but this is fine for now
            if (mod.propertyPath.StartsWith("_serializedStateValues.Array.data[")) {
                string front = mod.propertyPath.Remove(0, "_serializedStateValues.Array.data".Length + 1);
                string num = front.Substring(0, front.Length - 1);

                int index;
                if (int.TryParse(num, out index) &&
                    index >= 0 && index < obj.SerializedStateKeys.Count) {

                    keyName = obj.SerializedStateKeys[index];
                    return true;
                }
            }

            keyName = string.Empty;
            return false;
        }
Exemplo n.º 35
0
 private static bool TryExtractPropertyName(ISerializedObject obj, PropertyModification mod, out string keyName)
 {
     if (mod.propertyPath.StartsWith("_serializedStateValues.Array.data["))
     {
         string text = mod.propertyPath.Remove(0, "_serializedStateValues.Array.data".Length + 1);
         string s = text.Substring(0, text.Length - 1);
         int num;
         if (int.TryParse(s, out num) && num >= 0 && num < obj.SerializedStateKeys.Count)
         {
             keyName = obj.SerializedStateKeys[num];
             return true;
         }
     }
     keyName = string.Empty;
     return false;
 }
 private void EnsureRestored(ISerializedObject obj)
 {
     if (!obj.Restored)
     {
         bool flag = obj.SerializedStateKeys == null || obj.SerializedStateValues == null;
         obj.RestoreState();
         if (flag)
         {
             obj.SaveState();
         }
         ObjectModificationDetector.Update(obj);
         ISerializedObject serializedObject = PrefabUtility.GetPrefabParent(base.target) as ISerializedObject;
         if (serializedObject != null)
         {
             this.EnsureRestored(serializedObject);
         }
     }
     if (ObjectModificationDetector.WasModified(obj) && !EditorApplication.isPlaying)
     {
         obj.RestoreState();
         ObjectModificationDetector.Update(obj);
     }
 }
 private void DrawSerializedState(ISerializedObject behavior)
 {
     if (FullInspectorCommonSerializedObjectEditor._editorShowSerializedState)
     {
         ReorderableListFlags flags = ReorderableListFlags.HideAddButton;
         EditorGUILayout.HelpBox("The following is raw serialization data. Only change it if you know what you're doing or you could corrupt your object!", (MessageType)2);
         ReorderableListGUI.Title("Serialized Keys");
         ReorderableListGUI.ListField(new GenericListAdaptorWithDynamicHeight<string>(behavior.SerializedStateKeys, new ReorderableListControl.ItemDrawer<string>(this.DrawItem), new Func<string, float>(this.GetItemHeight), null), flags);
         ReorderableListGUI.Title("Serialized Values");
         ReorderableListGUI.ListField(new GenericListAdaptorWithDynamicHeight<string>(behavior.SerializedStateValues, new ReorderableListControl.ItemDrawer<string>(this.DrawItem), new Func<string, float>(this.GetItemHeight), null), flags);
         ReorderableListGUI.Title("Serialized Object References");
         ReorderableListGUI.ListField(new GenericListAdaptorWithDynamicHeight<UnityEngine.Object>(behavior.SerializedObjectReferences, new ReorderableListControl.ItemDrawer<UnityEngine.Object>(this.DrawItem), new Func<UnityEngine.Object, float>(this.GetItemHeight), null), flags);
     }
 }
Exemplo n.º 38
0
 /// <summary>
 /// 현재 개체가 동일한 형식의 다른 개체와 같은지 여부를 나타냅니다.
 /// </summary>
 /// <returns>
 /// 현재 개체가 <paramref name="other"/> 매개 변수와 같으면 true이고, 그렇지 않으면 false입니다.
 /// </returns>
 /// <param name="other">이 개체와 비교할 개체입니다.</param>
 public bool Equals(ISerializedObject other) {
     return (other != null) && GetHashCode().Equals(other.GetHashCode());
 }
Exemplo n.º 39
0
 public static void Update(ISerializedObject obj)
 {
     bool flag;
     long id = ObjectModificationDetector._ids.GetId(obj, out flag);
     ObjectModificationDetector._serializedStates[id] = ObjectModificationDetector.GetHash(obj);
 }
 public void AddObject(ISerializedObject obj)
 {
     _objects.Add(obj.ObjectId, obj);
 }
            public Object ReadRecord(ISerializedObject parent)
            {
                var recordType = (RecordTypeEnumeration)ReadByte();

                switch(recordType) {
                    case RecordTypeEnumeration.SerializedStreamHeader:
                        throw new InvalidOperationException("Unexpected record type SerializedStreamHeader at position " + (_reader.BaseStream.Position - 1));

                    case RecordTypeEnumeration.ClassWithId: { // 1
                        var obj = new ClassWithId(this);
                        AddObject(obj);
                        return obj;
                    }

                    case RecordTypeEnumeration.SystemClassWithMembersAndTypes: { // 4
                        var obj = new SystemClassWithMembersAndTypes(this);
                        AddObject(obj);
                        return obj;
                    }

                    case RecordTypeEnumeration.ClassWithMembersAndTypes: { // 5
                        var obj = new ClassWithMembersAndTypes(this);
                        Check.That(_libraries.ContainsKey(obj.LibraryId), "LibraryId not yet seen.");
                        AddObject(obj);
                        return obj;
                    }

                    case RecordTypeEnumeration.BinaryObjectString: { // 6
                        var obj = new BinaryObjectString(this);
                        AddObject(obj);
                        return obj;
                    }

                    case RecordTypeEnumeration.MemberPrimitiveTyped: { // 8
                        var obj = new MemberPrimitiveTyped(this);
                        return obj;
                    }

                    case RecordTypeEnumeration.MemberReference: { // 9
                        var obj = new MemberReference(this);
                        return obj;
                    }

                    case RecordTypeEnumeration.BinaryLibrary: { // 12
                        var obj = new BinaryLibrary(this);
                        _libraries.Add(obj.LibraryId, obj);
                        return null;
                    }

                    case RecordTypeEnumeration.ArraySinglePrimitive: { // 15
                        var obj = new ArraySinglePrimitive(this);
                        AddObject(obj);
                        return obj;
                    }

                    case RecordTypeEnumeration.ObjectNull: { // 16
                        return null;
                    }

                    case RecordTypeEnumeration.MessageEnd: { // 17
                        _eof = true;
                        return null;
                    }

                    default:
                        throw new NotSupportedException("Unsupported record type " + recordType + " at position " + (_reader.BaseStream.Position - 1));
                }
            }