Пример #1
0
 public string Export(bool format = true)
 {
     return(EditorJsonUtility.ToJson(this, format));
 }
Пример #2
0
 private void OnDisable()
 {
     EditorPrefs.SetString(SaveKey, EditorJsonUtility.ToJson(_cfg));
 }
        public void ToSubGraph()
        {
            var path = EditorUtility.SaveFilePanelInProject("Save subgraph", "New SubGraph", "ShaderSubGraph", "");

            path = path.Replace(Application.dataPath, "Assets");
            if (path.Length == 0)
            {
                return;
            }

            graphObject.RegisterCompleteObjectUndo("Convert To Subgraph");
            var graphView = graphEditorView.graphView;

            var nodes  = graphView.selection.OfType <MaterialNodeView>().Where(x => !(x.node is PropertyNode)).Select(x => x.node as INode).ToArray();
            var bounds = Rect.MinMaxRect(float.PositiveInfinity, float.PositiveInfinity, float.NegativeInfinity, float.NegativeInfinity);

            foreach (var node in nodes)
            {
                var center = node.drawState.position.center;
                bounds = Rect.MinMaxRect(
                    Mathf.Min(bounds.xMin, center.x),
                    Mathf.Min(bounds.yMin, center.y),
                    Mathf.Max(bounds.xMax, center.x),
                    Mathf.Max(bounds.yMax, center.y));
            }
            var middle = bounds.center;

            bounds.center = Vector2.zero;

            var copyPasteGraph = new CopyPasteGraph(
                graphView.selection.OfType <MaterialNodeView>().Where(x => !(x.node is PropertyNode)).Select(x => x.node as INode),
                graphView.selection.OfType <Edge>().Select(x => x.userData as IEdge));

            var deserialized = CopyPasteGraph.FromJson(JsonUtility.ToJson(copyPasteGraph, false));

            if (deserialized == null)
            {
                return;
            }

            var subGraph           = new SubGraph();
            var subGraphOutputNode = new SubGraphOutputNode();

            {
                var drawState = subGraphOutputNode.drawState;
                drawState.position           = new Rect(new Vector2(bounds.xMax + 200f, 0f), drawState.position.size);
                subGraphOutputNode.drawState = drawState;
            }
            subGraph.AddNode(subGraphOutputNode);

            var nodeGuidMap = new Dictionary <Guid, Guid>();

            foreach (var node in deserialized.GetNodes <INode>())
            {
                var oldGuid = node.guid;
                var newGuid = node.RewriteGuid();
                nodeGuidMap[oldGuid] = newGuid;
                var drawState = node.drawState;
                drawState.position = new Rect(drawState.position.position - middle, drawState.position.size);
                node.drawState     = drawState;
                subGraph.AddNode(node);
            }

            // figure out what needs remapping
            var externalOutputSlots = new List <IEdge>();
            var externalInputSlots  = new List <IEdge>();

            foreach (var edge in deserialized.edges)
            {
                var outputSlot = edge.outputSlot;
                var inputSlot  = edge.inputSlot;

                Guid remappedOutputNodeGuid;
                Guid remappedInputNodeGuid;
                var  outputSlotExistsInSubgraph = nodeGuidMap.TryGetValue(outputSlot.nodeGuid, out remappedOutputNodeGuid);
                var  inputSlotExistsInSubgraph  = nodeGuidMap.TryGetValue(inputSlot.nodeGuid, out remappedInputNodeGuid);

                // pasting nice internal links!
                if (outputSlotExistsInSubgraph && inputSlotExistsInSubgraph)
                {
                    var outputSlotRef = new SlotReference(remappedOutputNodeGuid, outputSlot.slotId);
                    var inputSlotRef  = new SlotReference(remappedInputNodeGuid, inputSlot.slotId);
                    subGraph.Connect(outputSlotRef, inputSlotRef);
                }

                // one edge needs to go to outside world
                else if (outputSlotExistsInSubgraph)
                {
                    externalInputSlots.Add(edge);
                }
                else if (inputSlotExistsInSubgraph)
                {
                    externalOutputSlots.Add(edge);
                }
            }

            // Find the unique edges coming INTO the graph
            var uniqueIncomingEdges = externalOutputSlots.GroupBy(
                edge => edge.outputSlot,
                edge => edge,
                (key, edges) => new { slotRef = key, edges = edges.ToList() });

            var externalInputNeedingConnection = new List <KeyValuePair <IEdge, IShaderProperty> >();

            foreach (var group in uniqueIncomingEdges)
            {
                var sr       = group.slotRef;
                var fromNode = graphObject.graph.GetNodeFromGuid(sr.nodeGuid);
                var fromSlot = fromNode.FindOutputSlot <MaterialSlot>(sr.slotId);

                IShaderProperty prop;
                switch (fromSlot.concreteValueType)
                {
                case ConcreteSlotValueType.Texture2D:
                    prop = new TextureShaderProperty();
                    break;

                case ConcreteSlotValueType.Cubemap:
                    prop = new CubemapShaderProperty();
                    break;

                case ConcreteSlotValueType.Vector4:
                    prop = new Vector4ShaderProperty();
                    break;

                case ConcreteSlotValueType.Vector3:
                    prop = new Vector3ShaderProperty();
                    break;

                case ConcreteSlotValueType.Vector2:
                    prop = new Vector2ShaderProperty();
                    break;

                case ConcreteSlotValueType.Vector1:
                    prop = new Vector1ShaderProperty();
                    break;

                case ConcreteSlotValueType.Boolean:
                    prop = new BooleanShaderProperty();
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }

                if (prop != null)
                {
                    var materialGraph    = (AbstractMaterialGraph)graphObject.graph;
                    var fromPropertyNode = fromNode as PropertyNode;
                    var fromProperty     = fromPropertyNode != null?materialGraph.properties.FirstOrDefault(p => p.guid == fromPropertyNode.propertyGuid) : null;

                    prop.displayName = fromProperty != null ? fromProperty.displayName : fromNode.name;
                    subGraph.AddShaderProperty(prop);
                    var propNode = new PropertyNode();
                    {
                        var drawState = propNode.drawState;
                        drawState.position = new Rect(new Vector2(bounds.xMin - 300f, 0f), drawState.position.size);
                        propNode.drawState = drawState;
                    }
                    subGraph.AddNode(propNode);
                    propNode.propertyGuid = prop.guid;

                    foreach (var edge in group.edges)
                    {
                        subGraph.Connect(
                            new SlotReference(propNode.guid, PropertyNode.OutputSlotId),
                            new SlotReference(nodeGuidMap[edge.inputSlot.nodeGuid], edge.inputSlot.slotId));
                        externalInputNeedingConnection.Add(new KeyValuePair <IEdge, IShaderProperty>(edge, prop));
                    }
                }
            }

            var uniqueOutgoingEdges = externalInputSlots.GroupBy(
                edge => edge.inputSlot,
                edge => edge,
                (key, edges) => new { slot = key, edges = edges.ToList() });

            var externalOutputsNeedingConnection = new List <KeyValuePair <IEdge, IEdge> >();

            foreach (var group in uniqueOutgoingEdges)
            {
                var outputNode = subGraph.outputNode;
                var slotId     = outputNode.AddSlot();

                var inputSlotRef = new SlotReference(outputNode.guid, slotId);

                foreach (var edge in group.edges)
                {
                    var newEdge = subGraph.Connect(new SlotReference(nodeGuidMap[edge.outputSlot.nodeGuid], edge.outputSlot.slotId), inputSlotRef);
                    externalOutputsNeedingConnection.Add(new KeyValuePair <IEdge, IEdge>(edge, newEdge));
                }
            }

            File.WriteAllText(path, EditorJsonUtility.ToJson(subGraph));
            AssetDatabase.ImportAsset(path);

            var loadedSubGraph = AssetDatabase.LoadAssetAtPath(path, typeof(MaterialSubGraphAsset)) as MaterialSubGraphAsset;

            if (loadedSubGraph == null)
            {
                return;
            }

            var subGraphNode = new SubGraphNode();
            var ds           = subGraphNode.drawState;

            ds.position            = new Rect(middle - new Vector2(100f, 150f), Vector2.zero);
            subGraphNode.drawState = ds;
            graphObject.graph.AddNode(subGraphNode);
            subGraphNode.subGraphAsset = loadedSubGraph;

            foreach (var edgeMap in externalInputNeedingConnection)
            {
                graphObject.graph.Connect(edgeMap.Key.outputSlot, new SlotReference(subGraphNode.guid, edgeMap.Value.guid.GetHashCode()));
            }

            foreach (var edgeMap in externalOutputsNeedingConnection)
            {
                graphObject.graph.Connect(new SlotReference(subGraphNode.guid, edgeMap.Value.inputSlot.slotId), edgeMap.Key.inputSlot);
            }

            graphObject.graph.RemoveElements(
                graphView.selection.OfType <MaterialNodeView>().Select(x => x.node as INode),
                Enumerable.Empty <IEdge>());
            graphObject.graph.ValidateGraph();
        }
Пример #4
0
 internal void Save(BuildTarget target)
 {
     target = ResolveTarget(target);
     File.WriteAllText(GetPath(target), EditorJsonUtility.ToJson(this, true));
 }
Пример #5
0
        public static NotificationSettingsManager Initialize()
        {
            if (s_SettingsManager != null)
            {
                return(s_SettingsManager);
            }

            var  settingsManager = CreateInstance <NotificationSettingsManager>();
            bool dirty           = false;

            if (File.Exists(k_SettingsPath))
            {
                var settingsJson = File.ReadAllText(k_SettingsPath);
                if (!string.IsNullOrEmpty(settingsJson))
                {
                    EditorJsonUtility.FromJsonOverwrite(settingsJson, settingsManager);
                }
            }
            else
            {
                // Only migrate if there is no new settings asset under k_SettingsPath.
                dirty = MigrateFromLegacySettings(settingsManager);
            }

            if (settingsManager.m_iOSNotificationSettingsValues == null)
            {
                settingsManager.m_iOSNotificationSettingsValues = new NotificationSettingsCollection();
                dirty = true;
            }

            if (settingsManager.m_AndroidNotificationSettingsValues == null)
            {
                settingsManager.m_AndroidNotificationSettingsValues = new NotificationSettingsCollection();
                dirty = true;
            }

            // Create the settings for iOS.
            settingsManager.iOSNotificationSettings = new List <NotificationSetting>()
            {
                new NotificationSetting(
                    "UnityNotificationRequestAuthorizationOnAppLaunch",
                    "Request Authorization on App Launch",
                    "It's recommended to make the authorization request during the app's launch cycle. If this is enabled the authorization pop-up will show up immediately during launching. Otherwise you need to manually create an AuthorizationRequest before sending or receiving notifications.",
                    settingsManager.GetOrAddNotificationSettingValue("UnityNotificationRequestAuthorizationOnAppLaunch", true, false),
                    dependencies: new List <NotificationSetting>()
                {
                    new NotificationSetting(
                        "UnityNotificationDefaultAuthorizationOptions",
                        "Default Notification Authorization Options",
                        "Configure the notification interaction types which will be included in the authorization request if \"Request Authorization on App Launch\" is enabled.",
                        settingsManager.GetOrAddNotificationSettingValue("UnityNotificationDefaultAuthorizationOptions",
                                                                         AuthorizationOption.Alert | AuthorizationOption.Badge | AuthorizationOption.Sound, false)),
                }),
                new NotificationSetting(
                    "UnityAddRemoteNotificationCapability",
                    "Enable Push Notifications",
                    "Enable this to add the push notification capability to the Xcode project, also to retrieve the device token from an AuthorizationRequest.",
                    settingsManager.GetOrAddNotificationSettingValue("UnityAddRemoteNotificationCapability", false, false),
                    false,
                    new List <NotificationSetting>()
                {
                    new NotificationSetting(
                        "UnityNotificationRequestAuthorizationForRemoteNotificationsOnAppLaunch",
                        "Register for Push Notifications on App Launch",
                        "Enable this to automatically register your app with APNs after launching to receive remote notifications. You need to manually create an AuthorizationRequest to get the device token.",
                        settingsManager.GetOrAddNotificationSettingValue("UnityNotificationRequestAuthorizationForRemoteNotificationsOnAppLaunch", false, false)),
                    new NotificationSetting(
                        "UnityRemoteNotificationForegroundPresentationOptions",
                        "Remote Notification Foreground Presentation Options",
                        "Configure the default presentation options for received remote notifications. In order to use the specified presentation options, your app must have received the authorization (the user might change it at any time).",
                        settingsManager.GetOrAddNotificationSettingValue("UnityRemoteNotificationForegroundPresentationOptions", (PresentationOption)iOSPresentationOption.All, false)),
                    new NotificationSetting("UnityUseAPSReleaseEnvironment",
                                            "Enable Release Environment for APS",
                                            "Enable this when signing the app with a production certificate.",
                                            settingsManager.GetOrAddNotificationSettingValue("UnityUseAPSReleaseEnvironment", false, false),
                                            false),
                }),
                new NotificationSetting("UnityUseLocationNotificationTrigger",
                                        "Include CoreLocation Framework",
                                        "Include the CoreLocation framework to use the iOSNotificationLocationTrigger in your project.",
                                        settingsManager.GetOrAddNotificationSettingValue("UnityUseLocationNotificationTrigger", false, false),
                                        false)
            };

            // Create the settings for Android.
            settingsManager.AndroidNotificationSettings = new List <NotificationSetting>()
            {
                new NotificationSetting(
                    "UnityNotificationAndroidRescheduleOnDeviceRestart",
                    "Reschedule on Device Restart",
                    "Enable this to automatically reschedule all non-expired notifications after device restart. By default AndroidSettings removes all scheduled notifications after restarting.",
                    settingsManager.GetOrAddNotificationSettingValue("UnityNotificationAndroidRescheduleOnDeviceRestart", false, true)),
                new NotificationSetting(
                    "UnityNotificationAndroidUseCustomActivity",
                    "Use Custom Activity",
                    "Enable this to override the activity which will be opened when the user taps the notification.",
                    settingsManager.GetOrAddNotificationSettingValue("UnityNotificationAndroidUseCustomActivity", false, true),
                    dependencies: new List <NotificationSetting>()
                {
                    new NotificationSetting(
                        "UnityNotificationAndroidCustomActivityString",
                        "Custom Activity Name",
                        "The full class name of the activity which will be assigned to the notification.",
                        settingsManager.GetOrAddNotificationSettingValue("UnityNotificationAndroidCustomActivityString", "com.unity3d.player.UnityPlayerActivity", true))
                })
            };

            settingsManager.SaveSettings(dirty);

            s_SettingsManager = settingsManager;
            return(s_SettingsManager);
        }
Пример #6
0
 static void UpdateNodeGraphOnDisk(string path, INodeGraph graph)
 {
     File.WriteAllText(path, EditorJsonUtility.ToJson(graph, true));
     AssetDatabase.ImportAsset(path);
 }
Пример #7
0
        internal static void SaveSettings()
        {
            var json = EditorJsonUtility.ToJson(s_Settings, true);

            File.WriteAllText("ProjectSettings/ScriptableBuildPipeline.json", json);
        }
        /// <summary>
        /// Copy components on the 'from' object which is the object being converted,
        /// over to the 'to' object which is the FBX.
        ///
        /// Copy over everything except meshes and materials, since these
        /// are already in the FBX.
        ///
        /// The 'from' hierarchy is not modified.
        ///
        /// Note: 'root' is the root object that is being converted
        /// </summary>
        internal static void CopyComponents(GameObject to, GameObject from, GameObject root, Dictionary <string, GameObject> nameMap)
        {
            // copy components on "from" to "to". Don't want to copy over meshes and materials that were exported
            var originalComponents    = new List <Component>(from.GetComponents <Component>());
            var destinationComponents = new List <Component>(to.GetComponents <Component>());

            foreach (var fromComponent in originalComponents)
            {
                // ignore missing components
                if (fromComponent == null)
                {
                    continue;
                }

                // ignore MeshFilter and Transform, but still ensure scene references are maintained.
                // Don't need to copy regular transform (except for the root object) as the values should already be correct in the FBX.
                // Furthermore, copying transform values may result in overrides in the prefab, which is undesired as if
                // the transform is updated in the FBX, it won't be in the prefab.
                if (fromComponent is MeshFilter || (fromComponent is Transform && from != root))
                {
                    FixSceneReferences(fromComponent, to.GetComponent(fromComponent.GetType()), root);
                    continue;
                }

                // ignore FbxPrefab (when converting LinkedPrefabs)
                // Also ignore RectTransform, since it is not currently possible to switch transforms
                // in a prefab.
                if (fromComponent is UnityEngine.Formats.Fbx.Exporter.FbxPrefab ||
                    fromComponent is RectTransform)
                {
                    continue;
                }

                var json = EditorJsonUtility.ToJson(fromComponent);
                if (string.IsNullOrEmpty(json))
                {
                    // this happens for missing scripts
                    continue;
                }

                System.Type expectedType = fromComponent.GetType();
                Component   toComponent  = null;

                // Find the component to copy to.
                for (int i = 0, n = destinationComponents.Count; i < n; i++)
                {
                    // ignore missing components
                    if (destinationComponents[i] == null)
                    {
                        continue;
                    }

                    if (destinationComponents[i].GetType() == expectedType)
                    {
                        // We have found the component we are looking for,
                        // remove it so we don't try to copy to it again
                        toComponent = destinationComponents[i];
                        destinationComponents.RemoveAt(i);
                        break;
                    }
                }

                // If it's a particle system renderer, then check to see if it hasn't already
                // been added when adding the particle system.
                // An object can have only one ParticleSystem so there shouldn't be an issue of the renderer
                // belonging to a different ParticleSystem.
                if (!toComponent && fromComponent is ParticleSystemRenderer)
                {
                    toComponent = to.GetComponent <ParticleSystemRenderer>();
                }

                if (!toComponent)
                {
                    toComponent = to.AddComponent(fromComponent.GetType());
                }

                if (!toComponent)
                {
                    // Failed to add component
                    Debug.LogWarningFormat("{0}: Failed to add component of type {1} to converted object", ModelExporter.PACKAGE_UI_NAME, fromComponent.GetType().Name);
                    continue;
                }

                FixSceneReferences(fromComponent, toComponent, root);

                // SkinnedMeshRenderer also stores the mesh.
                // Make sure this is not copied over when the SkinnedMeshRenderer is updated,
                // as we want to keep the mesh from the FBX not the scene.
                if (fromComponent is SkinnedMeshRenderer)
                {
                    var skinnedMesh = toComponent as SkinnedMeshRenderer;
                    var mesh        = skinnedMesh.sharedMesh;
                    EditorJsonUtility.FromJsonOverwrite(json, toComponent);
                    skinnedMesh.sharedMesh = mesh;
                }
                else
                {
                    EditorJsonUtility.FromJsonOverwrite(json, toComponent);
                }

                if (fromComponent is MeshCollider)
                {
                    // UNI-27534: This fixes the issue where the mesh collider would not update to point to the mesh in the fbx after export
                    // Point the mesh included in the mesh collider to the mesh in the FBX file, which is the same as the one in mesh filter
                    var fromMeshCollider = from.GetComponent <MeshCollider>();
                    var fromMeshFilter   = from.GetComponent <MeshFilter>();
                    // if the mesh collider isn't pointing to the same mesh as in the current mesh filter then don't
                    // do anything as it's probably pointing to a mesh in a different fbx
                    if (fromMeshCollider && fromMeshFilter && fromMeshCollider.sharedMesh == fromMeshFilter.sharedMesh)
                    {
                        var toFilter = to.GetComponent <MeshFilter>();
                        if (toFilter)
                        {
                            var toMeshCollider = toComponent as MeshCollider;
                            toMeshCollider.sharedMesh = toFilter.sharedMesh;
                        }
                    }
                }

                var serializedFromComponent = new SerializedObject(fromComponent);
                var serializedToComponent   = new SerializedObject(toComponent);
                var fromProperty            = serializedFromComponent.GetIterator();
                fromProperty.Next(true); // skip generic field
                // For SkinnedMeshRenderer, the bones array doesn't have visible children, but still needs to be copied over.
                // For everything else, filtering by visible children in the while loop and then copying properties that don't have visible children,
                // ensures that only the leaf properties are copied over. Copying other properties is not usually necessary and may break references that
                // were not meant to be copied.
                while (fromProperty.Next((fromComponent is SkinnedMeshRenderer)? fromProperty.hasChildren : fromProperty.hasVisibleChildren))
                {
                    if (!fromProperty.hasVisibleChildren)
                    {
                        // with Undo operations, copying m_Father reference causes issues. Also, it is not required as the reference is fixed when
                        // the transform is parented under the correct hierarchy (which happens before this).
                        if (fromProperty.propertyType == SerializedPropertyType.ObjectReference && fromProperty.propertyPath != "m_GameObject" &&
                            fromProperty.propertyPath != "m_Father" && fromProperty.objectReferenceValue &&
                            (fromProperty.objectReferenceValue is GameObject || fromProperty.objectReferenceValue is Component))
                        {
                            CopySerializedProperty(serializedToComponent, fromProperty, nameMap);
                        }
                    }
                }
            }
        }
Пример #9
0
        public static string Save(object obj)
        {
            if (obj == null)
            {
                return(string.Empty);
            }

            if (obj.GetType().IsPrimitive)
            {
                return(string.Format(CultureInfo.InvariantCulture, "{0}", obj));
            }
            else if (obj is UnityEngine.Object) //type is a unity object
            {
                if ((obj as UnityEngine.Object) == null)
                {
                    return(string.Empty);
                }
                ObjectWrapper wrapper = new ObjectWrapper {
                    obj = obj as UnityEngine.Object
                };
                var json = EditorJsonUtility.ToJson(wrapper);
                return(json);
            }
            else if (obj is AnimationCurve)
            {
                AnimCurveWrapper sac   = new AnimCurveWrapper();
                AnimationCurve   curve = obj as AnimationCurve;


                sac.frames = new AnimCurveWrapper.Keyframe[curve.keys.Length];
                for (int i = 0; i < curve.keys.Length; ++i)
                {
                    sac.frames[i].time             = curve.keys[i].time;
                    sac.frames[i].value            = curve.keys[i].value;
                    sac.frames[i].inTangent        = curve.keys[i].inTangent;
                    sac.frames[i].outTangent       = curve.keys[i].outTangent;
                    sac.frames[i].tangentMode      = 0; // Not used
                    sac.frames[i].leftTangentMode  = AnimationUtility.GetKeyLeftTangentMode(curve, i);
                    sac.frames[i].rightTangentMode = AnimationUtility.GetKeyRightTangentMode(curve, i);
                    sac.frames[i].broken           = AnimationUtility.GetKeyBroken(curve, i);
                }
                sac.preWrapMode  = curve.preWrapMode;
                sac.postWrapMode = curve.postWrapMode;
                sac.version      = 1;

                return(JsonUtility.ToJson(sac));
            }
            else if (obj is Gradient)
            {
                GradientWrapper gw       = new GradientWrapper();
                Gradient        gradient = obj as Gradient;

                gw.gradientMode = gradient.mode;
                gw.colorKeys    = new GradientWrapper.ColorKey[gradient.colorKeys.Length];
                for (int i = 0; i < gradient.colorKeys.Length; ++i)
                {
                    gw.colorKeys[i].color = gradient.colorKeys[i].color;
                    gw.colorKeys[i].time  = gradient.colorKeys[i].time;
                }
                gw.alphaKeys = new GradientWrapper.AlphaKey[gradient.alphaKeys.Length];
                for (int i = 0; i < gradient.alphaKeys.Length; ++i)
                {
                    gw.alphaKeys[i].alpha = gradient.alphaKeys[i].alpha;
                    gw.alphaKeys[i].time  = gradient.alphaKeys[i].time;
                }
                return(JsonUtility.ToJson(gw));
            }
            else if (obj is string)
            {
                return("\"" + ((string)obj).Replace("\"", "\\\"") + "\"");
            }
            else if (obj is SerializableType)
            {
                return("\"" + ((SerializableType)obj).text + "\"");
            }
            else if (obj.GetType().IsArrayOrList())
            {
                IList list = (IList)obj;

                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                sb.Append('[');
                for (int i = 0; i < list.Count; ++i)
                {
                    sb.Append(Save(list[i]));
                    sb.Append(',');
                }
                sb.Length = sb.Length - 1;
                sb.Append(']');

                return(sb.ToString());
            }
            else
            {
                return(EditorJsonUtility.ToJson(obj));
            }
        }
Пример #10
0
 public void OnBeforeSerialize()
 {
     m_SerializedMesh = EditorJsonUtility.ToJson(new MeshHelper {
         mesh = mesh
     }, false);
 }
Пример #11
0
        public void ShowGUI()
        {
            CustomGUILayout.MultiLineLabelGUI("Scene number:", sceneNumber.ToString());
            CustomGUILayout.MultiLineLabelGUI("Active NavMesh:", navMesh.ToString());
            CustomGUILayout.MultiLineLabelGUI("Default PlayerStart:", playerStart.ToString());
            CustomGUILayout.MultiLineLabelGUI("Default SortingMap:", sortingMap.ToString());
            CustomGUILayout.MultiLineLabelGUI("Default TintMap:", tintMap.ToString());
            CustomGUILayout.MultiLineLabelGUI("OnStart cutscene:", onStartCutscene.ToString());
            CustomGUILayout.MultiLineLabelGUI("OnLoadCutscene:", onLoadCutscene.ToString());

            EditorGUILayout.LabelField("Remember data:");
            if (allScriptData != null && allScriptData.Count > 0)
            {
                foreach (ScriptData scriptData in allScriptData)
                {
                    RememberData rememberData = SaveSystem.FileFormatHandler.DeserializeObject <RememberData> (scriptData.data);
                    if (rememberData != null)
                    {
                        CustomGUILayout.MultiLineLabelGUI("   " + rememberData.GetType().ToString() + ":", EditorJsonUtility.ToJson(rememberData, true));
                    }
                }
            }

            if (allTransformData != null && allTransformData.Count > 0)
            {
                foreach (TransformData transformData in allTransformData)
                {
                    CustomGUILayout.MultiLineLabelGUI("   " + transformData.GetType().ToString() + ":", EditorJsonUtility.ToJson(transformData, true));
                }
            }

            CustomGUILayout.MultiLineLabelGUI("Active ActionLists:", activeLists.ToString());
            CustomGUILayout.MultiLineLabelGUI("Local Variables:", localVariablesData);
        }
Пример #12
0
        static public string ConvertToJson(baseAchievement toConvert)
        {
            string json = "\"" + toConvert.sName + "\":" + EditorJsonUtility.ToJson(toConvert);

            return(json);
        }
Пример #13
0
 string ISupportedPostComponent.GetHashString()
 {
     return(EditorJsonUtility.ToJson(profile));
 }
Пример #14
0
        ////////////////////////////
        //! POSTPROCESSING COMPONENT GUI *** //

        void ISupportedPostComponent.LeftSideGUI(EditorWindow window, float width)
        {
            //profile = PostProcessingBehaviourOjbect.profile;
            profile = GetFieldValue("profile", PostProcessingBehaviourOjbect) as ScriptableObject;

            var changedProfile = EditorGUILayout.ObjectField(profile, Params.PostProcessingProfileType, false) as ScriptableObject;

            if (changedProfile != profile)
            {
                Undo.RecordObject(PostProcessingBehaviourOjbect, "Change PostProcessing Profile");
                profile = SetFieldValue("profile", PostProcessingBehaviourOjbect, changedProfile) as ScriptableObject;
                SetLast(changedProfile);
                EditorUtility.SetDirty(PostProcessingBehaviourOjbect);
                EditorUtility.SetDirty(Camera.main.gameObject);
            }

            GUILayout.BeginHorizontal(GUILayout.Width(width));
            for (int i = 0; i < LastList.Count; i++)
            {
                if (!LastList[i])
                {
                    continue;
                }
                var al = Params.Button.alignment;
                Params.Button.alignment = TextAnchor.MiddleLeft;
                var result = GUILayout.Button(Params.CONTENT(LastList[i].name, "Set " + LastList[i].name), Params.Button, GUILayout.Width(width / LastList.Count), GUILayout.Height(14));
                Params.Button.alignment = al;
                if (result)
                {
                    Undo.RecordObject(PostProcessingBehaviourOjbect, "Change PostProcessing Profile");
                    SetFieldValue("profile", PostProcessingBehaviourOjbect, LastList[i]);
                    EditorUtility.SetDirty(PostProcessingBehaviourOjbect);
                    EditorUtility.SetDirty(Camera.main.gameObject);
                }
                EditorGUIUtility.AddCursorRect(GUILayoutUtility.GetLastRect(), MouseCursor.Link);
            }
            GUILayout.EndHorizontal();

            //GUILayout.Space( 10 );
            GUILayout.BeginHorizontal(GUILayout.Width(width));
            if (GUILayout.Button(Params.CONTENT("Default Profile", "Set Default Profile")))
            {
                var defaultProfile = AssetDatabase.LoadAssetAtPath(Params.EditorResourcesPath + "/CameraProfile.asset", Params.PostProcessingProfileType) as ScriptableObject;
                if (!defaultProfile)
                {
                    defaultProfile = CreateProfile(Params.EditorResourcesPath + "/CameraProfile.asset");
                }
                Undo.RecordObject(PostProcessingBehaviourOjbect, "Change PostProcessing Profile");
                SetFieldValue("profile", PostProcessingBehaviourOjbect, defaultProfile);
                SetLast(defaultProfile);
                EditorUtility.SetDirty(PostProcessingBehaviourOjbect);
                EditorUtility.SetDirty(Camera.main.gameObject);
            }
            GUI.enabled = profile;
            if (GUILayout.Button(Params.CONTENT("New Copy", "Create and set a copy of current profile")))
            {
                var json       = EditorJsonUtility.ToJson(profile);
                var newProfile = CreateProfile(AssetDatabase.GenerateUniqueAssetPath("Assets/NewCameraProfile.asset"));
                EditorJsonUtility.FromJsonOverwrite(json, newProfile);
                EditorUtility.SetDirty(newProfile);
                Undo.RecordObject(PostProcessingBehaviourOjbect, "Change PostProcessing Profile");
                SetFieldValue("profile", PostProcessingBehaviourOjbect, newProfile);
                SetLast(newProfile);
                EditorUtility.SetDirty(PostProcessingBehaviourOjbect);
                EditorUtility.SetDirty(Camera.main.gameObject);
            }
            GUI.enabled = true;


            GUILayout.EndHorizontal();

            if (!profile)
            {
                return;
            }

            ModelType = GetField("fog", profile).FieldType.BaseType;

            if (!p_to_e.ContainsKey(profile))
            {
                p_to_e.Add(profile, Editor.CreateEditor(profile));
            }
            var e = p_to_e[profile];

            if (!e)
            {
                GUILayout.Label("Internal Plugin Error", Params.Label);
                return;
            }


            Params.AutoRefresh.Set(EditorGUILayout.ToggleLeft("Automatic refresh when changing", Params.AutoRefresh == 1) ? 1 : 0);


            GUILayout.Space(10);

            Params.scroll.x = Params.scrollX;
            Params.scroll.y = Params.scrollY;
            Params.scroll   = GUILayout.BeginScrollView(Params.scroll, alwaysShowVertical: true, alwaysShowHorizontal: false);
            Params.scrollX.Set(Params.scroll.x);
            Params.scrollY.Set(Params.scroll.y);
            e.OnInspectorGUI();
            GUILayout.EndScrollView();
        } //! POSTPROCESSING COMPONENT GUI
Пример #15
0
 public void OnBeforeSerialize()
 {
     m_SerializedCubemap = EditorJsonUtility.ToJson(new CubemapHelper {
         cubemap = cubemap
     }, false);
 }
Пример #16
0
        public static object Load(System.Type type, string text, object oldValue)
        {
            if (type == null)
            {
                return(null);
            }

            if (type.IsPrimitive)
            {
                if (string.IsNullOrEmpty(text))
                {
                    try
                    {
                        return(Activator.CreateInstance(type));
                    }
                    catch (MissingMethodException)
                    {
                        Debug.LogError(type.Name + " Doesn't seem to have a default constructor");

                        throw;
                    }
                }

                return(Convert.ChangeType(text, type, CultureInfo.InvariantCulture));
            }
            else if (typeof(UnityEngine.Object).IsAssignableFrom(type))
            {
                object obj = new ObjectWrapper();
                EditorJsonUtility.FromJsonOverwrite(text, obj);

                return(((ObjectWrapper)obj).obj);
            }
            else if (type.IsAssignableFrom(typeof(AnimationCurve)))
            {
                AnimCurveWrapper sac = new AnimCurveWrapper();

                JsonUtility.FromJsonOverwrite(text, sac);

                AnimationCurve curve = oldValue != null ? (AnimationCurve)oldValue : new AnimationCurve();

                if (sac.frames != null)
                {
                    Keyframe[] keys = new UnityEngine.Keyframe[sac.frames.Length];
                    for (int i = 0; i < sac.frames.Length; ++i)
                    {
                        keys[i].time       = sac.frames[i].time;
                        keys[i].value      = sac.frames[i].value;
                        keys[i].inTangent  = sac.frames[i].inTangent;
                        keys[i].outTangent = sac.frames[i].outTangent;
                        if (sac.version == 1)
                        {
                            AnimationUtility.SetKeyLeftTangentMode(ref keys[i], sac.frames[i].leftTangentMode);
                            AnimationUtility.SetKeyRightTangentMode(ref keys[i], sac.frames[i].rightTangentMode);
                            AnimationUtility.SetKeyBroken(ref keys[i], sac.frames[i].broken);
                        }
                        else
                        {
                            AnimationUtility.SetKeyLeftTangentMode(ref keys[i], (TangentMode)((sac.frames[i].tangentMode & kLeftTangentMask) >> 1));
                            AnimationUtility.SetKeyRightTangentMode(ref keys[i], (TangentMode)((sac.frames[i].tangentMode & kRightTangentMask) >> 5));
                            AnimationUtility.SetKeyBroken(ref keys[i], (sac.frames[i].tangentMode & kBrokenMask) != 0);
                        }
                    }
                    curve.keys         = keys;
                    curve.preWrapMode  = sac.preWrapMode;
                    curve.postWrapMode = sac.postWrapMode;
                }

                return(curve);
            }
            else if (type.IsAssignableFrom(typeof(Gradient)))
            {
                GradientWrapper gw       = new GradientWrapper();
                Gradient        gradient = oldValue != null ? (Gradient)oldValue : new Gradient();

                JsonUtility.FromJsonOverwrite(text, gw);

                gradient.mode = gw.gradientMode;

                GradientColorKey[] colorKeys = null;
                if (gw.colorKeys != null)
                {
                    colorKeys = new GradientColorKey[gw.colorKeys.Length];
                    for (int i = 0; i < gw.colorKeys.Length; ++i)
                    {
                        colorKeys[i].color = gw.colorKeys[i].color;
                        colorKeys[i].time  = gw.colorKeys[i].time;
                    }
                }
                else
                {
                    colorKeys = new GradientColorKey[0];
                }

                GradientAlphaKey[] alphaKeys = null;

                if (gw.alphaKeys != null)
                {
                    alphaKeys = new GradientAlphaKey[gw.alphaKeys.Length];
                    for (int i = 0; i < gw.alphaKeys.Length; ++i)
                    {
                        alphaKeys[i].alpha = gw.alphaKeys[i].alpha;
                        alphaKeys[i].time  = gw.alphaKeys[i].time;
                    }
                }
                else
                {
                    alphaKeys = new GradientAlphaKey[0];
                }

                gradient.SetKeys(colorKeys, alphaKeys);
                return(gradient);
            }
            else if (type == typeof(string))
            {
                if (string.IsNullOrEmpty(text))
                {
                    return("");
                }
                return(text.Substring(1, text.Length - 2).Replace("\\\"", "\""));
            }
            else if (type == typeof(SerializableType))
            {
                var obj = new SerializableType(text.Substring(1, text.Length - 2));
                return(obj);
            }
            else if (type.IsArrayOrList())
            {
                List <string> elements = ParseArray(text);

                if (elements == null)
                {
                    return(null);
                }
                if (type.IsArray)
                {
                    int listCount = elements.Count;

                    Array arrayObj = (Array)Activator.CreateInstance(type, new object[] { listCount });

                    for (int index = 0; index < listCount; index++)
                    {
                        arrayObj.SetValue(Load(type.GetElementType(), elements[index], null), index);
                    }

                    return(arrayObj);
                }
                else //List
                {
                    int   listCount = elements.Count;
                    IList listObj   = (IList)Activator.CreateInstance(type, new object[0]);
                    for (int index = 0; index < listCount; index++)
                    {
                        listObj.Add(Load(type.GetElementType(), elements[index], null));
                    }

                    return(listObj);
                }
            }
            else
            {
                try
                {
                    object obj = Activator.CreateInstance(type);
                    EditorJsonUtility.FromJsonOverwrite(text, obj);
                    return(obj);
                }
                catch (MissingMethodException)
                {
                    Debug.LogError(type.Name + " Doesn't seem to have a default constructor");

                    throw;
                }
            }
        }
Пример #17
0
 private void OnDisable()
 {
     File.WriteAllText(kSettingsPath, EditorJsonUtility.ToJson(this));
 }
Пример #18
0
 public void OnBeforeSerialize()
 {
     m_SerializedTexture = EditorJsonUtility.ToJson(new TextureHelper {
         textureArray = textureArray
     }, false);
 }
    private static void SaveSettings()
    {
        string json = EditorJsonUtility.ToJson(settings);

        EditorPrefs.SetString(settings_prefs_path, json);
    }
Пример #20
0
    private void OnDisable()
    {
        string json = EditorJsonUtility.ToJson(this);

        EditorPrefs.SetString("OWW_props", json);
    }
 void UpdateShaderGraphOnDisk(string path)
 {
     File.WriteAllText(path, EditorJsonUtility.ToJson(graphObject.graph, true));
     AssetDatabase.ImportAsset(path);
 }
 string ISupportedPostComponent.GetHashString()
 {
     return(EditorJsonUtility.ToJson(((ISupportedPostComponent)this).MonoComponent));
 }
Пример #23
0
 private static void SaveSettings()
 {
     EditorPrefs.SetString("PaintIn3D.Settings", EditorJsonUtility.ToJson(Settings));
 }
Пример #24
0
        public static void SaveStateToSessionState()
        {
            var shareState = StoreFactory.Get().state.shareState;

            SessionState.SetString(typeof(ConnectShareEditorWindow).Name, EditorJsonUtility.ToJson(shareState));
        }
Пример #25
0
 void SaveState()
 {
     EditorPrefs.SetString(EditorPerfsKey, EditorJsonUtility.ToJson(this));
 }
        public void ResetToDefaults()
        {
            UndoHandler.RegisterUndoableAction(this, "Reset To Defaults");

                        #if UNITY_EDITOR          // in UnityEditor use Presets or EditorJsonUtility
                        #if UNITY_2018_1_OR_NEWER // Presets were introduced in Unity 2018.1
                        #if UNITY_2019_3_OR_NEWER // GetDefaultForObject became obsolete in Unity 2019.3
            var presets = Preset.GetDefaultPresetsForObject(this);
            var preset  = presets.Length > 0 ? presets[0] : null;
                        #else
            var preset = Preset.GetDefaultForObject(this);
                        #endif

            // if no default preset has been assigned for preferences asset, then try finding a preset
            // in the same directory with the preferences asset
            if (preset == null)
            {
                var preferencesPath = AssetDatabase.GetAssetPath(this);
                var directoryPath   = FileUtility.GetParentDirectory(preferencesPath);
                var updateGuids     = AssetDatabase.FindAssets("t:Preset", ArrayExtensions.TempStringArray(directoryPath));
                for (int n = updateGuids.Length - 1; n >= 0; n--)
                {
                    var path = AssetDatabase.GUIDToAssetPath(updateGuids[n]);
                    preset = AssetDatabase.LoadAssetAtPath <Preset>(path);
                    if (!string.Equals(preset.GetTargetFullTypeName(), typeof(InspectorPreferences).FullName, StringComparison.OrdinalIgnoreCase))
                    {
                        preset = null;
                    }
                    else
                    {
                        break;
                    }
                }
            }

            if (preset != null)
            {
                preset.ApplyTo(this);
            }
            else
                        #endif
            {
                var freshInstance = CreateInstance <InspectorPreferences>();
                var jsonString    = EditorJsonUtility.ToJson(freshInstance);
                Platform.Active.Destroy(freshInstance);
                EditorJsonUtility.FromJsonOverwrite(jsonString, this);
            }
                        #else
            // at runtime use JsonUtility to reset values to those of a freshly created instance
            var freshInstance = CreateInstance <InspectorPreferences>();
            var jsonString    = JsonUtility.ToJson(freshInstance);
            Platform.Active.Destroy(freshInstance);
            JsonUtility.FromJsonOverwrite(jsonString, this);
                        #endif

            setupDone         = false;
            isFirstOnValidate = true;

            if (Event.current != null)
            {
                Setup();
            }

            Platform.Active.SetDirty(this);

            if (onSettingsChanged != null)
            {
                onSettingsChanged(this);
            }
        }
Пример #27
0
 public void Save()
 {
     File.WriteAllText(AssetPath, EditorJsonUtility.ToJson(this));
 }
Пример #28
0
        public void TestImportAsset(string unityLocalPath, string fullPath)
        {
            unityLocalPath = unityLocalPath.Replace("\\", "/");
            Debug.Log("Testing file: " + unityLocalPath);

            // invoke an import
            AssetDatabase.ImportAsset(unityLocalPath, ImportAssetOptions.ForceSynchronousImport | ImportAssetOptions.ForceUpdate | ImportAssetOptions.DontDownloadFromCacheServer);

            // double check we can load it up and validate it
            string fileContents = File.ReadAllText(fullPath);

            Assert.Greater(fileContents.Length, 0);

            var       graphGuid      = AssetDatabase.AssetPathToGUID(unityLocalPath);
            var       messageManager = new MessageManager();
            GraphData graphData      = new GraphData()
            {
                assetGuid = graphGuid, messageManager = messageManager
            };

            MultiJson.Deserialize(graphData, fileContents);
            graphData.OnEnable();
            graphData.ValidateGraph();

            string fileExtension = Path.GetExtension(fullPath).ToLower();
            bool   isSubgraph    = (fileExtension == "shadersubgraph");

            if (isSubgraph)
            {
                // check that the SubGraphAsset is the same after versioning twice
                // this is important to ensure we're not importing subgraphs non-deterministically when they are out-of-date on disk
                AssetDatabase.ImportAsset(unityLocalPath, ImportAssetOptions.ForceSynchronousImport | ImportAssetOptions.ForceUpdate | ImportAssetOptions.DontDownloadFromCacheServer);
                var subGraph   = AssetDatabase.LoadAssetAtPath <SubGraphAsset>(unityLocalPath);
                var serialized = EditorJsonUtility.ToJson(subGraph);

                AssetDatabase.ImportAsset(unityLocalPath, ImportAssetOptions.ForceSynchronousImport | ImportAssetOptions.ForceUpdate | ImportAssetOptions.DontDownloadFromCacheServer);
                var subGraph2   = AssetDatabase.LoadAssetAtPath <SubGraphAsset>(unityLocalPath);
                var serialized2 = EditorJsonUtility.ToJson(subGraph2);

                Assert.AreEqual(serialized, serialized2, $"Importing the subgraph {unityLocalPath} twice resulted in different subgraph assets.");
            }
            else
            {
                // check that the generated shader is the same after versioning twice
                // this is important to ensure we're not importing shaders non-deterministically when they are out-of-date on disk
                string fileNameNoExtension = Path.GetFileNameWithoutExtension(fullPath);
                var    generator           = new Generator(graphData, graphData.outputNode, GenerationMode.ForReals, fileNameNoExtension, null);
                string shader = generator.generatedShader;

                // version again
                GraphData graphData2 = new GraphData()
                {
                    assetGuid = graphGuid, messageManager = messageManager
                };
                MultiJson.Deserialize(graphData2, fileContents);
                graphData2.OnEnable();
                graphData2.ValidateGraph();
                var    generator2 = new Generator(graphData2, graphData2.outputNode, GenerationMode.ForReals, fileNameNoExtension, null);
                string shader2    = generator2.generatedShader;

                Assert.AreEqual(shader, shader2, $"Importing the graph {unityLocalPath} twice resulted in different generated shaders.");

                // Texture test won't work on platforms that don't support more than 16 samplers

                bool isGL =
                    (SystemInfo.graphicsDeviceType == GraphicsDeviceType.OpenGLCore) ||
                    (SystemInfo.graphicsDeviceType == GraphicsDeviceType.OpenGLES2) ||
                    (SystemInfo.graphicsDeviceType == GraphicsDeviceType.OpenGLES3);

                bool isOSX =
                    (Application.platform == RuntimePlatform.OSXEditor) ||
                    (Application.platform == RuntimePlatform.OSXPlayer);

                bool samplersSupported = !(isOSX && isGL);
                if (!samplersSupported && fullPath.Contains("TextureTest"))
                {
                    // skip the compile test -- we know this shader won't compile on these platforms
                }
                else
                {
                    // now create a Unity Shader from the string
                    var compiledShader = ShaderUtil.CreateShaderAsset(shader, true);
                    compiledShader.hideFlags = HideFlags.HideAndDontSave;

                    Assert.NotNull(compiledShader);

                    // compile all the shader passes to see if there are any errors
                    var mat = new Material(compiledShader)
                    {
                        hideFlags = HideFlags.HideAndDontSave
                    };
                    for (int pass = 0; pass < mat.passCount; pass++)
                    {
                        ShaderUtil.CompilePass(mat, pass, true);
                    }
                }
            }
        }
Пример #29
0
    protected void OnDisable()
    {
        string path = Path.GetDirectoryName(Application.dataPath) + _settingsPath;

        File.WriteAllText(path, EditorJsonUtility.ToJson(_previewGenerator, true));
    }
Пример #30
0
        internal static DriverResponse HandleDriverRequest(DriverRequest request)
        {
            var response = new DriverResponse {
                method = request.method
            };
            var session = GetSession();

            switch (request.method.ToLowerInvariant())
            {
            case "registereditor":
                if (string.IsNullOrEmpty(session))
                {
                    SaveSession(request.session);
                    response.session = request.session;
                }
                else
                {
                    response.session = session;
                }

                response.result = "unity";
                break;

            case "exist":
                response.result = ExecuteGameObjectEmulation(request.root, request.name, request.parent, request.upath,
                                                             gameObject => true.ToString(), false.ToString());
                break;

            case "active":
                response.result = ExecuteGameObjectEmulation(request.root, request.name, request.parent, request.upath,
                                                             gameObject => gameObject.activeInHierarchy.ToString(), false.ToString());
                break;

            case "onscreen":
                response.result = ExecuteGameObjectEmulation(request.root, request.name, request.parent, request.upath, go =>
                {
                    return(ScreenHelper.IsOnScreen(go).ToString());
                }, "False");
                break;

            case "clickable":
                response.result = ExecuteGameObjectEmulation(request.root, request.name, request.parent, request.upath, go =>
                {
                    return(ScreenHelper.IsGraphicClickable(go).ToString());
                }, "False");
                break;

            case "getcomponent":
                response.result = ExecuteGameObjectEmulation(request.root, request.name, request.parent, request.upath, gameObject =>
                {
                    var component = gameObject.GetComponent(request.value);
                    return(component != null ? EditorJsonUtility.ToJson(component) : "null");
                });
                break;

            case "click":
                response.result = ExecuteGameObjectEmulation(request.root, request.name, request.parent, request.upath, go =>
                {
                    var pointer = new PointerEventData(EventSystem.current);
                    ExecuteEvents.Execute(go, pointer, ExecuteEvents.pointerClickHandler);
                    return(SuccessResult);
                });
                break;

            case "isrendering":
                response.result = ExecuteGameObjectEmulation(request.root, request.name, request.parent, request.upath,
                                                             go =>
                {
                    var renderer = go.GetComponent <Renderer>();
                    if (renderer != null)
                    {
                        return(renderer.isVisible.ToString());
                    }

                    return(false.ToString());
                });
                break;

            case "count":
                response.result = ExecuteGameObjectsEmulation(request.root, request.name, request.parent, request.upath, goList => goList.Count.ToString());
                break;

            case "deletepref":
                response.result = InvokeOnMainThreadAndWait(() =>
                {
                    PlayerPrefs.DeleteKey(request.value);
                    PlayerPrefs.Save();
                });
                break;

            case "deleteallprefs":
                response.result = InvokeOnMainThreadAndWait(() =>
                {
                    PlayerPrefs.DeleteAll();
                    PlayerPrefs.Save();
                });
                break;

            case "swipe":
                var swipeDirection = Vector2.zero;
                switch (request.value)
                {
                case "up":
                    swipeDirection = Vector2.up;
                    break;

                case "down":
                    swipeDirection = Vector2.down;
                    break;

                case "left":
                    swipeDirection = Vector2.left;
                    break;

                case "right":
                    swipeDirection = Vector2.right;
                    break;
                }

                swipeDirection *= 100;

                response.result = ExecuteGameObjectEmulation(request.root, request.name, request.parent, request.upath, go =>
                {
                    var pointer = new PointerEventData(EventSystem.current);

                    var rt = (RectTransform)go.transform;

                    Vector3[] corners = new Vector3[4];
                    rt.GetWorldCorners(corners);
                    var bottomLeft  = Camera.main.WorldToScreenPoint(corners[0]);
                    var topLeft     = Camera.main.WorldToScreenPoint(corners[1]);
                    var topRight    = Camera.main.WorldToScreenPoint(corners[2]);
                    var bottomRight = Camera.main.WorldToScreenPoint(corners[3]);

                    var center = new Vector2(topLeft.x + (bottomRight.x - topLeft.x) / 2,
                                             bottomRight.y + (topLeft.y - bottomRight.y) / 2);

                    go.GetComponent <MonoBehaviour>()
                    .StartCoroutine(DragCoroutine(go, pointer, center, swipeDirection));

                    return(SuccessResult);
                });
                break;


            case "sendkeys":
                response.result = ExecuteGameObjectEmulation(request.root, request.name, request.parent, request.upath, go =>
                {
                    var input = go.GetComponent <InputField>();
                    if (input != null)
                    {
                        input.text = request.value;
                    }
                    else
                    {
                        return("input not found");
                    }

                    return(SuccessResult);
                });
                break;

            case "startplaymode":
                EditorApplication.update += StartPlayMode;
                response.result           = SuccessResult;
                break;

            case "stopplaymode":
                response.result = InvokeOnMainThreadAndWait(() =>
                {
                    EditorApplication.UnlockReloadAssemblies();
                    EditorApplication.isPlaying = false;
                });

                break;

            case "ping":
                response.result = "pong";
                break;

            case "takescreenshot":
                var path = request.value;
                MainThreadHelper.QueueOnMainThread(() => { TakeScreenshot(path); });
                response.result = SuccessResult;
                break;

            default:
                response.result = "Unknown method " + request.method + ".";
                break;
            }

            return(response);
        }