public static void Save() { EditorPrefs.SetString("P3dWindow", EditorJsonUtility.ToJson(Instance)); }
static void SaveStateToSessionState() { var shareState = StoreFactory.get().state.shareState; SessionState.SetString(typeof(ConnectShareEditorWindow).Name, EditorJsonUtility.ToJson(shareState)); }
//////////////////////////// //! 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
string ISupportedPostComponent.GetHashString() { return(EditorJsonUtility.ToJson(((ISupportedPostComponent)this).MonoComponent)); }
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); }
void UpdateAbstractSubgraphOnDisk(string path) { File.WriteAllText(path, EditorJsonUtility.ToJson(graphObject.graph, true)); AssetDatabase.ImportAsset(path); }
// CALLBACK METHODS: ---------------------------------------------------------------------- public static void OnRetrieveUpdate(bool isError, UpdateHttpRequest.OutputData data) { CHECKING_UPDATES = false; if (isError || data == null || data.error) { return; } EditorPrefs.SetString(KEY_UPDATE_CACHE, EditorJsonUtility.ToJson(data.data)); if (GameCreatorUpdateWindow.WINDOW != null) { GameCreatorUpdateWindow.WINDOW.Refresh(); } Version skipVersion = new Version(EditorPrefs.GetString(KEY_SKIP_PACKAGE_VERSION, "0.0.0")); if (data.data.version.Equals(skipVersion) && GameCreatorUpdateWindow.WINDOW == null) { return; } if (data.data.version.HigherThan(Config.GetCurrent().version)) { string message = string.Empty; switch (data.data.type) { case "patch": message = PATCH; break; case "release": message = RELEASE; break; case "alpha": message = ALPHA; break; } int option = EditorUtility.DisplayDialogComplex( "New Game Creator version available.", message, "Download " + data.data.version, "Skip version", "Remind me tomorrow" ); switch (option) { case 0: Application.OpenURL(URL_DOWNLOAD); break; case 1: SkipVersion(data.data.version); break; case 2: SaveCheckTime(); break; } } else if (GameCreatorUpdateWindow.WINDOW != null) { EditorUtility.DisplayDialog( "Game Creator is up to date.", string.Format( "You're currently using {0}, which is the latest version.", Config.GetCurrent().version ), "Ok" ); } }
//Comment public static void EditorCopy <T>(T value) { EditorGUIUtility.systemCopyBuffer = EditorJsonUtility.ToJson(value); }
private void SaveSplitterState() { UserSettings.References.splitterState = EditorJsonUtility.ToJson(splitterState, false); }
public void OnBeforeSerialize() { m_SerializedTexture = EditorJsonUtility.ToJson(new TextureHelper { textureArray = textureArray }, false); }
void OnGUI() { EditorGUILayout.LabelField("ComponentBrowser", new GUIStyle() { fontStyle = FontStyle.Bold }); var active = Selection.activeGameObject; UpdateSelectItemsIfNeeded(active); scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition); EditorGUILayout.BeginHorizontal(); inputAsText = EditorGUILayout.ToggleLeft("input Type as text:", inputAsText, GUILayout.ExpandWidth(false)); GUI.enabled = inputAsText; var s = EditorGUILayout.TextField(inputTypeStr); EditorGUILayout.EndHorizontal(); GUI.enabled = !GUI.enabled; compSelection = GUILayout.SelectionGrid(compSelection, selectContents, 5, // new GUIStyle(GUI.skin.button) { alignment = TextAnchor.MiddleLeft }, // GUILayout.ExpandWidth(false)); GUI.enabled = true; Type type = null; if (inputAsText) { if (s != inputTypeStr) { inputTypeStr = s; inputType = TypeByName(s); } type = inputType; } else { if (compSelection < selectTypes.Length) // if activeGameObject == null then Length = 0, compSelection = 0 { type = selectTypes[compSelection]; } } drawType(type); EditorGUILayout.EndScrollView(); EditorGUILayout.BeginHorizontal(); using (new EditorGUI.DisabledScope(!(compSelection < selectTypes.Length))) { if (GUILayout.Button("Copy as JSON", GUILayout.ExpandWidth(false))) { GUIUtility.systemCopyBuffer = JsonUtility.ToJson(active.GetComponent(selectTypes[compSelection]), true); } if (GUILayout.Button("Copy with EditorJsonUtility", GUILayout.ExpandWidth(false))) { GUIUtility.systemCopyBuffer = EditorJsonUtility.ToJson(active.GetComponent(selectTypes[compSelection]), true); } } EditorGUILayout.EndHorizontal(); }
private static void Send(EventName eventName, object eventData) { if (!RegisterEvents()) { return; } var result = EditorAnalytics.SendEventWithLimit(eventName.ToString(), eventData); if (result == AnalyticsResult.Ok) { #if UNITY_TINY_INTERNAL Console.WriteLine($"Analytics: event='{eventName}', time='{DateTime.Now:HH:mm:ss}', payload={EditorJsonUtility.ToJson(eventData, true)}"); #endif } else { TraceError($"failed to send event {eventName}. Result: {result}"); } }
private static void Send(EventName eventName, object eventData) { #if SCENE_TEMPLATE_ANALYTICS_LOGGING #else if (SceneTemplateUtils.IsDeveloperMode()) { return; } #endif if (!RegisterEvents()) { #if SCENE_TEMPLATE_ANALYTICS_LOGGING Console.WriteLine($"[ST] Analytics disabled: event='{eventName}', time='{DateTime.Now:HH:mm:ss}', payload={EditorJsonUtility.ToJson(eventData, true)}"); #endif return; } try { var result = EditorAnalytics.SendEventWithLimit(eventName.ToString(), eventData); if (result == AnalyticsResult.Ok) { #if SCENE_TEMPLATE_ANALYTICS_LOGGING Console.WriteLine($"[ST] Event='{eventName}', time='{DateTime.Now:HH:mm:ss}', payload={EditorJsonUtility.ToJson(eventData, true)}"); #endif } else { Console.WriteLine($"[ST] Failed to send event {eventName}. Result: {result}"); } } catch (Exception) { // ignored } }
static public string ConvertToJson(baseAchievement toConvert) { string json = "\"" + toConvert.sName + "\":" + EditorJsonUtility.ToJson(toConvert); return(json); }
public UdonGraphElementData GetData() { return(new UdonGraphElementData(UdonGraphElementType.UdonGroup, uid, EditorJsonUtility.ToJson(_customData))); }
public string ExportAsJsonString() { return(EditorJsonUtility.ToJson(this)); }
public static void RefreshPackages() { if (_Packages == null) { // Load cache if (System.IO.File.Exists("EditorOutput/Runtime/packages.txt")) { try { var json = System.IO.File.ReadAllText("EditorOutput/Runtime/packages.txt"); PackagesInfoList list = new PackagesInfoList(); EditorJsonUtility.FromJsonOverwrite(json, list); List <UnityEditor.PackageManager.PackageInfo> packages = list.Packages; if (packages.Count > 0) { var newinfos = new Dictionary <string, UnityEditor.PackageManager.PackageInfo>(); for (int i = 0; i < packages.Count; ++i) { var package = packages[i]; newinfos[package.name] = package; } _Packages = newinfos; _OnPackagesChanged(); } } catch { } } } var req = UnityEditor.PackageManager.Client.List(true); EditorBridge.TerminableUpdate += () => { if (req.IsCompleted) { var newinfos = new Dictionary <string, UnityEditor.PackageManager.PackageInfo>(); foreach (var package in req.Result) { newinfos[package.name] = package; } if (_Packages == null || PackagesChanged(_Packages, newinfos)) { // Save cache try { System.IO.Directory.CreateDirectory("EditorOutput/Runtime/"); List <UnityEditor.PackageManager.PackageInfo> packages = new List <UnityEditor.PackageManager.PackageInfo>(newinfos.Values); PackagesInfoList list = new PackagesInfoList(); list.Packages = packages; var json = EditorJsonUtility.ToJson(list, true); System.IO.File.WriteAllText("EditorOutput/Runtime/packages.txt", json); } catch { } _Packages = newinfos; _OnPackagesChanged(); } //else //{ // _Packages = newinfos; //} return(true); } else { return(false); } }; }
/// <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); } } } } }
static void UpdateShaderGraphOnDisk(string path, GraphData graph) { File.WriteAllText(path, EditorJsonUtility.ToJson(graph, true)); AssetDatabase.ImportAsset(path); }
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.Contains("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); } Object.DestroyImmediate(mat); } } }
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; // Collect the property nodes and get the corresponding properties var propertyNodeGuids = graphView.selection.OfType <MaterialNodeView>().Where(x => (x.node is PropertyNode)).Select(x => ((PropertyNode)x.node).propertyGuid); var metaProperties = graphView.graph.properties.Where(x => propertyNodeGuids.Contains(x.guid)); var copyPasteGraph = new CopyPasteGraph( graphView.graph.guid, 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), graphView.selection.OfType <BlackboardField>().Select(x => x.userData as IShaderProperty), metaProperties); 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.Texture2DArray: prop = new Texture2DArrayShaderProperty(); break; case ConcreteSlotValueType.Texture3D: prop = new Texture3DShaderProperty(); 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(); }
public override void OnInspectorGUI() { base.OnInspectorGUI(); // UIManager manager = target as UIManager; GUILayout.Space(20); GUILayout.Label("インスタンスキャッシュ", EditorStyles.boldLabel); using (new EditorGUILayout.VerticalScope(EditorStyles.helpBox)) { foreach (var ui in UIManager.pooledObjects) { using (new EditorGUILayout.VerticalScope(EditorStyles.helpBox)) { // using (new EditorGUILayout.HorizontalScope()) { EditorGUILayout.ObjectField(ui, typeof(UIBase), true); if (ui.isInitialized) { GUILayout.Label(EditorGUIUtility.FindTexture("d_preaudioloopon"), GUILayout.Width(20)); } else { GUILayout.Label(EditorGUIUtility.FindTexture("d_preaudioloopoff"), GUILayout.Width(20)); } } // if (GUILayout.Button(EditorGUIUtility.FindTexture("unityeditor.consolewindow"), EditorStyles.label)) // { // Debug.Log(EditorJsonUtility.ToJson(ui.argument, false)); // } // EditorGUILayout.Toggle("サスペンド?", ui.isResourceLoaded); // GUILayout.TextArea(EditorJsonUtility.ToJson(ui.argument, false)); } } } GUILayout.Space(20); GUILayout.Label("アクティブ", EditorStyles.boldLabel); if (UIManager.currentScreen) { using (new EditorGUILayout.VerticalScope(EditorStyles.helpBox)) { foreach (var ui in UIManager.currentScreen.GetEnumrator()) { using (new EditorGUILayout.VerticalScope(EditorStyles.helpBox)) { GUILayout.Label(ui.name, EditorStyles.boldLabel); EditorGUILayout.ObjectField(ui, typeof(UIBase), true); if (ui.isTransiting) { GUILayout.Label("遷移中", "sv_label_2"); } else if (ui.isShow) { GUILayout.Label("表示済み", "sv_label_1"); } //else if(ui.isResourceLoaded) //GUILayout.Label("ロード済", "sv_label_5"); else if (ui.isInitialized) { GUILayout.Label("初期化済", "sv_label_6"); } else { GUILayout.Label("-", "sv_label_0"); } // EditorGUILayout.Toggle("初期化済?", ui.isInitialized); // EditorGUILayout.Toggle("ロード済?", ui.isResourceLoaded); // EditorGUILayout.Toggle("表示済?", ui.isMovedIn); GUILayout.TextArea(EditorJsonUtility.ToJson(ui.argument, false)); } } } } GUILayout.Space(20); GUILayout.Label("スクリーン履歴", EditorStyles.boldLabel); using (new EditorGUILayout.VerticalScope(EditorStyles.helpBox)) { foreach (var arg in UIManager.screenHistory) { using (new EditorGUILayout.VerticalScope(EditorStyles.helpBox)) { GUILayout.Label(arg.path, EditorStyles.boldLabel); var ui = UIManager.pooledObjects.Find(x => x.argument == arg); if (ui) { if (ui.isInitialized) { GUILayout.Label(EditorGUIUtility.FindTexture("d_preaudioloopon"), GUILayout.Width(20)); } else { GUILayout.Label(EditorGUIUtility.FindTexture("d_preaudioloopoff"), GUILayout.Width(20)); } } GUILayout.TextArea(EditorJsonUtility.ToJson(arg, false)); } } } if (Application.isPlaying) { Repaint(); } }
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)); } }
void SaveState() { EditorPrefs.SetString(EditorPerfsKey, EditorJsonUtility.ToJson(this)); }
public void OnBeforeSerialize() { m_SerializedCubemap = EditorJsonUtility.ToJson(new CubemapHelper { cubemap = cubemap }, false); }
public static void SaveUserPrefs() { EditorPrefs.SetString("TCP2_GlobalOptions", EditorJsonUtility.ToJson(data)); }
public string Export(bool format = true) { return(EditorJsonUtility.ToJson(this, format)); }
private static void Send(EventName eventName, object eventData) { if (!RegisterEvents()) { #if QUICKSEARCH_ANALYTICS_LOGGING Console.WriteLine($"[QS] Analytics disabled: event='{eventName}', time='{DateTime.Now:HH:mm:ss}', payload={EditorJsonUtility.ToJson(eventData, true)}"); #endif return; } try { var result = EditorAnalytics.SendEventWithLimit(eventName.ToString(), eventData); if (result == AnalyticsResult.Ok) { #if QUICKSEARCH_ANALYTICS_LOGGING Console.WriteLine($"[QS] Event='{eventName}', time='{DateTime.Now:HH:mm:ss}', payload={EditorJsonUtility.ToJson(eventData, true)}"); #endif } else { Console.WriteLine($"[QS] Failed to send event {eventName}. Result: {result}"); } } catch (Exception) { // ignored } }
string ISupportedPostComponent.GetHashString() { return(EditorJsonUtility.ToJson(profile)); }
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); }