private void Initialize() { data = new RefactorData(); var graphPrefabs = uNodeEditorUtility.FindPrefabsOfType <uNodeRoot>(); foreach (var prefab in graphPrefabs) { var gameObject = prefab; if (GraphUtility.HasTempGraphObject(prefab)) { gameObject = GraphUtility.GetTempGraphObject(prefab); } var scripts = gameObject.GetComponentsInChildren <MonoBehaviour>(true); Func <object, bool> scriptValidation = (obj) => { MemberData member = obj as MemberData; if (member != null) { FindMissingMember(member, false); } return(false); }; Array.ForEach(scripts, script => { data.missingTarget.Add(script); AnalizerUtility.AnalizeObject(script, scriptValidation); }); } }
internal static void OnInitialize() { GraphUtility.Initialize(); EditorSceneManager.newSceneCreated += onNewSceneCreated; EditorSceneManager.sceneClosing += onSceneClosing; EditorSceneManager.sceneSaving += onSceneSaving; EditorSceneManager.sceneSaved += onSceneSaved; EditorSceneManager.sceneOpening += onSceneOpening; EditorSceneManager.sceneOpened += onSceneOpened; }
/// <summary> /// Save the runtime graph to a prefab /// </summary> /// <param name="runtimeGraph"></param> /// <param name="graphAsset"></param> public static void SaveRuntimeGraph(uNodeRuntime runtimeGraph) { if (!Application.isPlaying) { throw new System.Exception("Saving runtime graph can only be done in playmode"); } if (runtimeGraph.originalGraph == null) { throw new System.Exception("Cannot save runtime graph because the original graph was null / missing"); } var graph = runtimeGraph.originalGraph; if (!EditorUtility.IsPersistent(graph)) { throw new System.Exception("Cannot save graph to unpersistent asset"); } var prefabContent = PrefabUtility.LoadPrefabContents(AssetDatabase.GetAssetPath(graph)); var originalGraph = uNodeHelper.GetGraphComponent(prefabContent, graph.GraphName); if (originalGraph != null) { if (runtimeGraph.RootObject != null) { //Duplicate graph data var tempRoot = Object.Instantiate(runtimeGraph.RootObject); tempRoot.name = "Root"; //Move graph data to original graph tempRoot.transform.SetParent(originalGraph.transform); //Retarget graph data owner AnalizerUtility.RetargetNodeOwner(runtimeGraph, originalGraph, tempRoot.GetComponentsInChildren <MonoBehaviour>(true)); if (originalGraph.RootObject != null) { //Destroy old graph data Object.DestroyImmediate(originalGraph.RootObject); } //Update graph data to new originalGraph.RootObject = tempRoot; //Save the graph to prefab uNodeEditorUtility.SavePrefabAsset(prefabContent, graph); //GraphUtility.DestroyTempGraphObject(originalGraph.gameObject); //This will update the original graph GraphUtility.DestroyTempGraphObject(graph.gameObject); //Refresh uNode Editor window uNodeEditor.window?.Refresh(); } } else { Debug.LogError("Cannot save instanced graph because the cannot find original graph with id:" + graph.GraphName); } PrefabUtility.UnloadPrefabContents(prefabContent); }
/// <summary> /// Save the temporary graph object into the original prefab /// </summary> /// <param name="graph"></param> public static void SaveTemporaryGraph(GameObject graph) { var asset = GraphUtility.GetOriginalObject(graph); if (asset != null) { SaveGraphAsset(asset, graph); } else { Debug.Log("Cannot save temporary graph: " + graph.name + " because the original graph cannot be found."); } }
public static CodeGenerator.GeneratedData[] GenerateProjectScripts( bool force, string label = "Generating C# Scripts", bool clearProgressOnFinish = true) { try { List <UnityEngine.Object> objects = new List <UnityEngine.Object>(); objects.AddRange(uNodeEditorUtility.FindPrefabsOfType <uNodeComponentSystem>()); objects.AddRange(uNodeEditorUtility.FindAssetsByType <uNodeInterface>()); int count = 0; var scripts = objects.Select(g => { count++; if (g is GameObject gameObject) { var graphs = gameObject.GetComponents <uNodeRoot>(); var targetData = gameObject.GetComponent <uNodeData>(); if (targetData != null || graphs.Select(gr => GraphUtility.GetGraphSystem(gr)).All(s => !s.allowAutoCompile) || graphs.Any(gr => !gr.graphData.compileToScript)) { return(null); } return(GenerateCSharpScript(gameObject, force, (progress, text) => { EditorUtility.DisplayProgressBar($"{label} {count}-{objects.Count}", text, progress); })); } else if (g is uNodeInterface iface) { EditorUtility.DisplayProgressBar($"Generating interface {iface.name} {count}-{objects.Count}", "", 1); return(GenerateCSharpScript(iface)); } else { throw new InvalidOperationException(g.GetType().FullName); } }).Where(s => s != null); return(scripts.ToArray()); } finally { if (clearProgressOnFinish) { uNodeThreadUtility.QueueOnFrame(() => { EditorUtility.ClearProgressBar(); }); } } }
public static CodeGenerator.GeneratedData GenerateCSharpScript(GameObject gameObject, bool force = true, Action <float, string> updateProgress = null) { if (uNodeEditorUtility.IsPrefab(gameObject)) { GameObject temp; if (GraphUtility.HasTempGraphObject(gameObject)) { temp = GraphUtility.GetTempGraphObject(gameObject); } else { GameObject goRoot = GameObject.Find("[@GRAPHS]"); if (goRoot == null) { goRoot = new GameObject("[@GRAPHS]"); goRoot.hideFlags = HideFlags.HideAndDontSave; uNodeThreadUtility.Queue(() => { if (goRoot != null) { GameObject.DestroyImmediate(goRoot); } }); } temp = PrefabUtility.InstantiatePrefab(gameObject, goRoot.transform) as GameObject; temp.SetActive(false); } var roots = temp.GetComponents <uNodeRoot>(); var targetData = temp.GetComponent <uNodeData>(); return(GenerateCSharpScript(roots, targetData, force, updateProgress)); } else { var roots = gameObject.GetComponents <uNodeRoot>(); var targetData = gameObject.GetComponent <uNodeData>(); return(GenerateCSharpScript(roots, targetData, force, updateProgress)); } }
void OnGUI() { if (targetField == null && targetObject != null) { FindTargetField(); } if (targetField == null || targetObject == null) { ShowNotification(new GUIContent("No target")); return; } if (targetField != null && targetObject != null) { scrollPos = EditorGUILayout.BeginScrollView(scrollPos); if (targetField is UnityEngine.Object) { uNodeGUIUtility.EditUnityObject(targetField as UnityEngine.Object); } else { uNodeGUIUtility.ShowFields(targetField, targetObject); if (targetField is InterfaceFunction) { var iFunc = targetField as InterfaceFunction; VariableEditorUtility.DrawParameter(iFunc.parameters, targetObject, null, (PD) => { iFunc.parameters = PD; }); if (targetObject is uNodeRoot) { var system = GraphUtility.GetGraphSystem(targetObject as uNodeRoot); if (system.supportGeneric) { VariableEditorUtility.DrawGenericParameter(iFunc.genericParameters, targetObject, (GPD) => { iFunc.genericParameters = GPD.ToArray(); }); } } else if (targetObject is uNodeData) { VariableEditorUtility.DrawGenericParameter(iFunc.genericParameters, targetObject, (GPD) => { iFunc.genericParameters = GPD.ToArray(); }); } } else if (targetField is Block) { string des = (targetField as Block).GetDescription(); if (!string.IsNullOrEmpty(des)) { EditorGUILayout.Space(); EditorGUILayout.HelpBox((targetField as Block).GetDescription(), MessageType.None, true); } } } //if(targetField is EventAction) { // System.Reflection.FieldInfo field = targetField.GetType().GetField("Name"); // uNodeEditorUtility.ShowField(field, targetField, targetObject); //} EditorGUILayout.EndScrollView(); uNodeEditorUtility.MarkDirty(targetObject); if (!focus) { GUI.FocusControl(null); EditorGUI.FocusTextInControl(null); focus = true; } if (GUI.changed) { if (onChanged != null) { onChanged(targetField); } uNodeGUIUtility.GUIChanged(targetObject); } } }
public override void OnInspectorGUI() { uNodeRoot root = target as uNodeRoot; EditorGUI.BeginDisabledGroup(uNodeEditorUtility.IsPrefab(root)); EditorGUI.BeginChangeCheck(); CustomInspector.DrawGraphInspector(root); if (EditorGUI.EndChangeCheck()) { uNodeEditor.GUIChanged(); } EditorGUI.EndDisabledGroup(); if (uNodeEditorUtility.IsPrefab(root)) { if (root is uNodeRuntime) { EditorGUILayout.HelpBox("Open Prefab to Edit Graph", MessageType.Info); } else { if (GUILayout.Button(new GUIContent("Open uNode Editor", "Open uNode Editor to edit this uNode"), EditorStyles.toolbarButton)) { uNodeEditor.ChangeTarget(target as uNodeRoot, true); } EditorGUILayout.HelpBox("Open uNode Editor to Edit values", MessageType.Info); } } else { if (GUILayout.Button(new GUIContent("Open uNode Editor", "Open uNode Editor to edit this uNode"), EditorStyles.toolbarButton)) { uNodeEditor.ChangeTarget(target as uNodeRoot, true); } } if (!Application.isPlaying && (root is uNodeRuntime || root is ISingletonGraph)) { var type = root.GeneratedTypeName.ToType(false); if (type != null) { EditorGUILayout.HelpBox("Run using Native C#", MessageType.Info); } else { EditorGUILayout.HelpBox("Run using Reflection", MessageType.Info); } } else if (Application.isPlaying && root is uNodeComponentSingleton singleton && (singleton.runtimeBehaviour != null || singleton.runtimeInstance != null)) { EditorGUI.DropShadowLabel(uNodeGUIUtility.GetRect(), "Runtime Component"); if (singleton.runtimeBehaviour == null) { uNodeGUIUtility.DrawVariablesInspector(singleton.runtimeInstance.Variables, singleton.runtimeInstance, null); } else if (singleton.runtimeBehaviour != null) { Editor editor = Editor.CreateEditor(singleton.runtimeBehaviour); if (editor != null) { editor.OnInspectorGUI(); } else { uNodeGUIUtility.ShowFields(singleton.runtimeBehaviour, singleton.runtimeBehaviour); } } } if (!Application.isPlaying && root is IIndependentGraph) { var system = GraphUtility.GetGraphSystem(root); if (system != null && system.allowAutoCompile && uNodeEditorUtility.IsPrefab(root)) { var actualGraph = root; if (GraphUtility.HasTempGraphObject(root.gameObject)) { actualGraph = GraphUtility.GetTempGraphObject(root); } uNodeGUIUtility.ShowField(new GUIContent("Compile to C#", "If true, the graph will be compiled to C# to run using native c# performance on build or in editor using ( Generate C# Scripts ) menu."), nameof(root.graphData.compileToScript), actualGraph.graphData, actualGraph); } } }
private void ReloadTabbar() { if (tabbarContainer != null) { tabbarContainer.RemoveFromHierarchy(); } tabbarContainer = new VisualElement() { name = "tabbar-container" }; tabbarContainer.style.left = _tabPosition; tabbarContainer.AddStyleSheet("uNodeStyles/Tabbar"); tabbarContainer.AddStyleSheet(UIElementUtility.Theme.tabbarStyle); var tabbar = new VisualElement() { name = "tabbar" }; { #region Main/Selection Tab if (window.mainGraph != null && window.mainGraph == window.selectedGraph && !window.mainGraph.selectedData.isValidGraph) { window.mainGraph.owner = null; window.mainGraph.graph = null; window.mainGraph.selectedData = new GraphEditorData(); } var tabMainElement = new ClickableElement("\"Main\"") { name = "tab-element", onClick = () => { window.ChangeEditorTarget(null); }, }; tabMainElement.AddManipulator(new ContextualMenuManipulator((evt) => { evt.menu.AppendAction("Close All But This", (act) => { window.graphs.Clear(); window.ChangeEditorTarget(null); ReloadTabbar(); }, DropdownMenuAction.AlwaysEnabled); evt.menu.AppendSeparator(""); evt.menu.AppendAction("Find Object", (act) => { EditorGUIUtility.PingObject(window.mainGraph.owner); ReloadTabbar(); }, DropdownMenuAction.AlwaysEnabled); evt.menu.AppendAction("Select Object", (act) => { EditorGUIUtility.PingObject(window.mainGraph.owner); Selection.activeObject = window.mainGraph.owner; ReloadTabbar(); }, DropdownMenuAction.AlwaysEnabled); })); if (window.selectedGraph == window.mainGraph) { tabMainElement.AddToClassList("tab-selected"); } tabbar.Add(tabMainElement); #endregion for (int i = 0; i < window.graphs.Count; i++) { var graph = window.graphs[i]; try { if (graph == null || graph.owner == null || !graph.selectedData.isValidGraph) { window.graphs.RemoveAt(i); i--; continue; } } catch { window.graphs.RemoveAt(i); i--; continue; } var tabElement = new ClickableElement(graph.displayName) { name = "tab-element", onClick = () => { window.ChangeEditorTarget(graph); }, }; tabElement.AddManipulator(new ContextualMenuManipulator((evt) => { evt.menu.AppendAction("Close", (act) => { var oldData = window.selectedGraph; window.graphs.Remove(graph); window.ChangeEditorTarget(oldData); ReloadTabbar(); }, DropdownMenuAction.AlwaysEnabled); evt.menu.AppendAction("Close All", (act) => { window.graphs.Clear(); window.ChangeEditorTarget(null); ReloadTabbar(); }, DropdownMenuAction.AlwaysEnabled); evt.menu.AppendAction("Close Others", (act) => { var current = window.selectedGraph; window.graphs.Clear(); window.graphs.Add(current); window.ChangeEditorTarget(current); ReloadTabbar(); }, DropdownMenuAction.AlwaysEnabled); evt.menu.AppendSeparator(""); evt.menu.AppendAction("Find Object", (act) => { EditorGUIUtility.PingObject(graph.owner); ReloadTabbar(); }, DropdownMenuAction.AlwaysEnabled); evt.menu.AppendAction("Select Object", (act) => { EditorGUIUtility.PingObject(graph.owner); Selection.activeObject = graph.owner; ReloadTabbar(); }, DropdownMenuAction.AlwaysEnabled); })); if (window.selectedGraph == graph) { tabElement.AddToClassList("tab-selected"); } tabbar.Add(tabElement); } #region Plus Tab { var plusElement = new ClickableElement("+") { name = "tab-element", }; { plusElement.menu = new DropdownMenu(); plusElement.menu.AppendAction("Open...", (act) => { window.OpenNewGraphTab(); ReloadTabbar(); }); #region Recent Files List <UnityEngine.Object> lastOpenedObjects = uNodeEditor.FindLastOpenedGraphs(); for (int i = 0; i < lastOpenedObjects.Count; i++) { var obj = lastOpenedObjects[i]; if (obj is uNodeRoot) { uNodeRoot root = obj as uNodeRoot; plusElement.menu.AppendAction("Open Recent/" + root.gameObject.name, (act) => { uNodeEditor.ChangeTarget(root, true); }); } else if (obj is uNodeData) { uNodeData data = obj as uNodeData; plusElement.menu.AppendAction("Open Recent/" + data.gameObject.name, (act) => { uNodeEditor.ChangeTarget(data, true); }); } } if (lastOpenedObjects.Count > 0) { plusElement.menu.AppendSeparator("Open Recent/"); plusElement.menu.AppendAction("Open Recent/Clear Recent", (act) => { uNodeEditor.ClearLastOpenedGraphs(); }); } #endregion var graphSystem = GraphUtility.FindGraphSystemAttributes(); int lastOrder = int.MinValue; for (int i = 0; i < graphSystem.Count; i++) { var g = graphSystem[i]; if (i == 0 || Mathf.Abs(g.order - lastOrder) >= 10) { plusElement.menu.AppendSeparator(""); } lastOrder = g.order; plusElement.menu.AppendAction(g.menu, (act) => { string path = EditorUtility.SaveFilePanelInProject("Create " + g.menu, "", "prefab", ""); if (!string.IsNullOrEmpty(path)) { GameObject go = new GameObject(); go.name = path.Split('/').Last().Split('.')[0]; go.AddComponent(g.type); GameObject prefab = PrefabUtility.SaveAsPrefabAsset(go, path); UnityEngine.Object.DestroyImmediate(go); AssetDatabase.SaveAssets(); EditorUtility.FocusProjectWindow(); uNodeEditor.ChangeTarget(prefab.GetComponent(g.type) as uNodeRoot); } }); } } tabbar.Add(plusElement); } #endregion } var pathbar = new VisualElement() { name = "pathbar" }; if (editorData.graph != null) { var graph = new ClickableElement(editorData.graph.DisplayName) { name = "path-element" }; graph.AddToClassList("path-graph"); { graph.menu = new DropdownMenu(); uNodeRoot[] graphs = editorData.graphs; if (graphs == null) { return; } for (int i = 0; i < graphs.Length; i++) { var g = graphs[i]; if (g == null) { continue; } graph.menu.AppendAction(g.DisplayName, (act) => { if (g == editorData.graph) { window.ChangeEditorSelection(g); } else { uNodeEditor.ChangeTarget(g); } }, (act) => { if (g == editorData.graph) { return(DropdownMenuAction.Status.Checked); } return(DropdownMenuAction.Status.Normal); }); } } Type graphIcon = typeof(TypeIcons.GraphIcon); if (editorData.graph is IClass) { IClass classSystem = editorData.graph as IClass; graphIcon = classSystem.IsStruct ? typeof(TypeIcons.StructureIcon) : typeof(TypeIcons.ClassIcon); } graph.ShowIcon(uNodeEditorUtility.GetTypeIcon(graphIcon)); graph.EnableBreadcrumb(true); pathbar.Add(graph); var root = window.selectedGraph.selectedData.selectedRoot; var function = new ClickableElement(root != null ? root.Name : editorData.graph is IStateGraph state && state.canCreateGraph ? "[State Graph]" : editorData.graph is IMacroGraph ? "[MACRO]" : "[NO ROOT]") { name = "path-element" }; function.AddToClassList("path-function"); { function.menu = new DropdownMenu(); if (editorData.graph is IStateGraph stateGraph && stateGraph.canCreateGraph) { function.menu.AppendAction("[State Graph]", (act) => { if (editorData.selectedRoot != null || editorData.selectedGroup != null) { editorData.selected = null; editorData.selectedRoot = null; Refresh(); UpdatePosition(); } window.ChangeEditorSelection(null); }, (act) => { if (editorData.selectedRoot == null) { return(DropdownMenuAction.Status.Checked); } return(DropdownMenuAction.Status.Normal); }); } List <RootObject> roots = new List <RootObject>(); roots.AddRange(editorData.graph.Functions); roots.Sort((x, y) => string.Compare(x.Name, y.Name)); for (int i = 0; i < roots.Count; i++) { var r = roots[i]; if (r == null) { continue; } function.menu.AppendAction(r.Name, (act) => { if (editorData.currentCanvas == r) { window.ChangeEditorSelection(r); } else { editorData.selectedRoot = r; SelectionChanged(); Refresh(); UpdatePosition(); } }, (act) => { if (r == editorData.selectedRoot) { return(DropdownMenuAction.Status.Checked); } return(DropdownMenuAction.Status.Normal); }); } } function.ShowIcon(uNodeEditorUtility.GetTypeIcon(root == null ? typeof(TypeIcons.StateIcon) : typeof(TypeIcons.MethodIcon))); pathbar.Add(function); if (editorData.graph != null && editorData.selectedGroup && editorData.selectedGroup.owner == editorData.graph) { function.EnableBreadcrumb(true); List <Node> GN = new List <Node>(); GN.Add(editorData.selectedGroup); NodeEditorUtility.FindParentNode(editorData.selectedGroup.transform, ref GN, editorData.graph); for (int i = GN.Count - 1; i >= 0; i--) { var nestedGraph = GN[i]; var element = new ClickableElement(nestedGraph.GetNodeName()) { name = "path-element", onClick = () => { window.ChangeEditorSelection(nestedGraph); if (editorData.selectedGroup != nestedGraph) { editorData.selectedGroup = nestedGraph; Refresh(); UpdatePosition(); } } }; element.AddToClassList("path-nested"); element.ShowIcon(uNodeEditorUtility.GetTypeIcon(nestedGraph.GetNodeIcon())); pathbar.Add(element); if (i != 0) { element.EnableBreadcrumb(true); } } } } else { var graph = new ClickableElement("[NO GRAPH]") { name = "path-element" }; pathbar.Add(graph); } tabbarContainer.Add(tabbar); tabbarContainer.Add(pathbar); window.rootVisualElement.Add(tabbarContainer); tabbarContainer.SendToBack(); }
public static void CompileNativeGraph(GameObject graphObject, bool enableLogging = true) { string fileName = graphObject.name; GameObject prefabContent = null; var go = graphObject; if (uNodeEditorUtility.IsPrefab(graphObject)) { if (GraphUtility.HasTempGraphObject(graphObject)) { go = GraphUtility.GetTempGraphObject(graphObject); } else { prefabContent = PrefabUtility.LoadPrefabContents(AssetDatabase.GetAssetPath(graphObject)); go = prefabContent; } } else if (GraphUtility.IsTempGraphObject(graphObject)) { graphObject = GraphUtility.GetOriginalObject(graphObject); } uNodeRoot renamedRoot = null; { var root = go.GetComponent <uNodeRoot>(); if (root && string.IsNullOrEmpty(root.Name)) { root.Name = fileName; renamedRoot = root; } } Directory.CreateDirectory(GenerationUtility.tempFolder); char separator = Path.DirectorySeparatorChar; string path = GenerationUtility.tempFolder + separator + fileName + ".cs"; try { System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch(); watch.Start(); var script = GenerationUtility.GenerateCSharpScript(go, true, (progress, text) => { EditorUtility.DisplayProgressBar("Loading", text, progress); }); List <ScriptInformation> informations; var generatedScript = script.ToScript(out informations); if (preferenceData.generatorData.convertLineEnding) { generatedScript = GenerationUtility.ConvertLineEnding(generatedScript, Application.platform != RuntimePlatform.WindowsEditor); } if (preferenceData.generatorData != null && preferenceData.generatorData.analyzeScript && preferenceData.generatorData.formatScript) { var codeFormatter = TypeSerializer.Deserialize("MaxyGames.uNode.Editors.CSharpFormatter", false); if (codeFormatter != null) { var str = codeFormatter. GetMethod("FormatCode"). Invoke(null, new object[] { generatedScript }) as string; generatedScript = str; } } using (StreamWriter sw = new StreamWriter(path)) { sw.Write(generatedScript); sw.Close(); } watch.Stop(); if (enableLogging) { Debug.LogFormat("Generating C# took {0,8:N3} s.", watch.Elapsed.TotalSeconds); } if (preferenceData.generatorData.compileScript) { bool isBecauseOfAccessibility = false; try { watch.Reset(); watch.Start(); EditorUtility.DisplayProgressBar("Loading", "Compiling", 1); var compileResult = CompileScript(generatedScript); if (compileResult.assembly == null) { isBecauseOfAccessibility = true; foreach (var error in compileResult.errors) { if (error.errorNumber != "CS0122") { isBecauseOfAccessibility = false; break; } } throw new Exception(compileResult.GetErrorMessage()); } watch.Stop(); #if !NET_STANDARD_2_0 if (enableLogging) { Debug.LogFormat("Compiling script took {0,8:N3} s.", watch.Elapsed.TotalSeconds); } #endif } catch (System.Exception ex) { watch.Stop(); EditorUtility.ClearProgressBar(); if (EditorUtility.DisplayDialog("Compile Errors", "Compile before save detect an error: \n" + ex.Message + "\n\n" + (isBecauseOfAccessibility ? "The initial errors may because of using a private class.\nWould you like to ignore the error and save it?" : "Would you like to ignore the error and save it?"), "Ok, save it", "No, don't save")) { Debug.Log("Compile errors: " + ex.Message); } else { Debug.Log("Temp script saved to: " + Path.GetFullPath(path)); throw ex; } } } if (EditorUtility.IsPersistent(graphObject)) //For prefab and asset { path = (Path.GetDirectoryName(AssetDatabase.GetAssetPath(graphObject)) + separator + fileName + ".cs"); if (informations != null) { uNodeEditor.SavedData.RegisterGraphInfos(informations, script.graphOwner, path); } using (FileStream stream = File.Open(path, FileMode.Create, FileAccess.Write)) { using (StreamWriter writer = new StreamWriter(stream)) { writer.Write(generatedScript); writer.Close(); } stream.Close(); } } else //For the scene object. { path = EditorUtility.SaveFilePanel("Save Script", "Assets", fileName + ".cs", "cs"); if (informations != null) { uNodeEditor.SavedData.RegisterGraphInfos(informations, script.graphOwner, path); } using (FileStream stream = File.Open(path, FileMode.Create, FileAccess.Write)) { using (StreamWriter writer = new StreamWriter(stream)) { writer.Write(generatedScript); writer.Close(); } stream.Close(); } } AssetDatabase.Refresh(); Debug.Log("Script saved to: " + Path.GetFullPath(path)); EditorUtility.ClearProgressBar(); } catch { EditorUtility.ClearProgressBar(); Debug.LogError("Aborting Generating C# Script because have error."); throw; } finally { if (renamedRoot) { renamedRoot.Name = ""; } if (prefabContent != null) { PrefabUtility.UnloadPrefabContents(prefabContent); } } }
public static void GenerateCSharpScriptForSceneGraphs() { DeleteGeneratedCSharpScriptForScenes(); //Removing previous files so there's no outdated scripts var scenes = EditorBuildSettings.scenes; var dir = generatedPath + Path.DirectorySeparatorChar + "Scripts.Scenes"; // uNodeEditorUtility.FindAssetsByType<SceneAsset>(); for (int i = 0; i < scenes.Length; i++) { var scene = scenes[i]; var sceneAsset = AssetDatabase.LoadAssetAtPath <SceneAsset>(scene.path); if (sceneAsset == null || !scene.enabled) { continue; } EditorUtility.DisplayProgressBar($"Loading Scene: {sceneAsset.name} {i+1}-{scenes.Length}", "", 0); while (uNodeThreadUtility.IsNeedUpdate()) { uNodeThreadUtility.Update(); } GraphUtility.DestroyTempGraph(); var currentScene = EditorSceneManager.OpenScene(scene.path); var graphs = GameObject.FindObjectsOfType <uNodeComponentSystem>().Select(item => item.gameObject).Distinct().ToArray(); var scripts = new List <CodeGenerator.GeneratedData>(); int count = 0; foreach (var graph in graphs) { count++; scripts.Add(GenerationUtility.GenerateCSharpScript(graph, true, (progress, info) => { EditorUtility.DisplayProgressBar($"Generating C# for: {sceneAsset.name} {i+1}-{scenes.Length} current: {count}-{graphs.Length}", info, progress); })); } while (uNodeThreadUtility.IsNeedUpdate()) { uNodeThreadUtility.Update(); } GraphUtility.DestroyTempGraph(); EditorSceneManager.SaveScene(currentScene); EditorUtility.DisplayProgressBar("Saving Scene Scripts", "", 1); Directory.CreateDirectory(dir); var startPath = Path.GetFullPath(dir) + Path.DirectorySeparatorChar; foreach (var script in scripts) { var path = startPath + currentScene.name + "_" + script.fileName + ".cs"; int index = 1; while (File.Exists(path)) //Ensure name to be unique { path = startPath + currentScene.name + "_" + script.fileName + index + ".cs"; index++; } using (StreamWriter sw = new StreamWriter(path)) { List <ScriptInformation> informations; var generatedScript = script.ToScript(out informations); if (informations != null) { uNodeEditor.SavedData.RegisterGraphInfos(informations, script.graphOwner, path); } sw.Write(GenerationUtility.ConvertLineEnding(generatedScript, false)); sw.Close(); } } } AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); EditorUtility.ClearProgressBar(); Debug.Log("Successful generating scenes script, existing scenes graphs will run with native c#." + "\nRemember to compiles the graph again if you made a changes to a graphs to keep the script up to date." + "\nRemoving generated scripts will makes the graph to run with reflection again." + "\nGenerated scenes script can be found on: " + dir); }
void Init(bool autoLayout) { if (config.type is RuntimeType) { if (config.owner.targetNode.owner.IsRuntimeGraph()) { var field = new ObjectRuntimeField() { objectType = config.type as RuntimeType, value = config.value as UnityEngine.Object, allowSceneObjects = uNodeEditorUtility.IsSceneObject(config.owner.targetNode) }; field.RegisterValueChangedCallback((e) => { config.OnValueChanged(e.newValue); MarkDirtyRepaint(); }); Add(field); } else { var button = new Label() { text = "null" }; button.AddToClassList("PopupButton"); button.EnableInClassList("Layout", autoLayout); Add(button); // if(config.value != null) { // try { // config.OnValueChanged(null); // } catch{ } // } } } else { ObjectField field = new ObjectField() { objectType = config.type, value = config.value as UnityEngine.Object, }; field.RegisterValueChangedCallback((e) => { config.OnValueChanged(e.newValue); MarkDirtyRepaint(); }); field.allowSceneObjects = uNodeEditorUtility.IsSceneObject(config.owner.targetNode) && !GraphUtility.IsTempGraphObject(config.owner.targetNode.gameObject); Add(field); } }
// static bool hasCompilingInit; internal static void Initialize() { // EditorBinding.onFinishCompiling += () => { // if(!hasCompilingInit) { // SaveAllGraph(false); // hasCompilingInit = true; // } // }; CodeGenerator.OnSuccessGeneratingGraph += (generatedData, settings) => { if (settings.isPreview) { return; } foreach (var graph in generatedData.graphs) { if (generatedData.classNames.TryGetValue(graph, out var className)) { graph.graphData.typeName = settings.nameSpace.Add(".") + className; uNodeEditorUtility.MarkDirty(graph); //this will ensure the graph will be saved if (HasTempGraphObject(graph.gameObject)) { var tempGraph = GraphUtility.GetTempGraphObject(graph); if (tempGraph != null) { tempGraph.graphData.typeName = graph.graphData.typeName; } } // if (!settings.isAsync) { // Skip on generating in background // graph.graphData.lastCompiled = UnityEngine.Random.Range(1, int.MaxValue); // graph.graphData.lastSaved = graph.graphData.lastCompiled; // } } } }; EditorBinding.onSceneSaving += (UnityEngine.SceneManagement.Scene scene, string path) => { //Save all graph. SaveAllGraph(false); TempGraphManager.OnSaving(); }; EditorBinding.onSceneSaved += (UnityEngine.SceneManagement.Scene scene) => { //After scene is saved, back the temp graph flag to hide in hierarchy. // TempGraphManager.managerObject.hideFlags = HideFlags.HideInHierarchy; uNodeUtility.TempManagement.DestroyTempObjets(); TempGraphManager.OnSaved(); }; EditorBinding.onSceneClosing += (UnityEngine.SceneManagement.Scene scene, bool removingScene) => { SaveAllGraph(); uNodeUtility.TempManagement.DestroyTempObjets(); }; EditorBinding.onSceneOpening += (string path, UnityEditor.SceneManagement.OpenSceneMode mode) => { SaveAllGraph(); uNodeUtility.TempManagement.DestroyTempObjets(); }; EditorBinding.onSceneOpened += (UnityEngine.SceneManagement.Scene scene, UnityEditor.SceneManagement.OpenSceneMode mode) => { DestroyTempGraph(); uNodeUtility.TempManagement.DestroyTempObjets(); }; EditorApplication.quitting += () => { SaveAllGraph(true); uNodeUtility.TempManagement.DestroyTempObjets(); uNodeEditorUtility.SaveEditorData("", "EditorTabData"); }; }
private static void RefactorFunction(uNodeFunction function, string name, Type returnType, Type[] paramTypes) { var graph = function.owner; Undo.SetCurrentGroupName("Refactor Function: " + function.Name); HashSet <GameObject> referencedGraphs = new HashSet <GameObject>(); if (graph != null) { RuntimeMethod runtime = null; if (graph is IIndependentGraph) { if (GraphUtility.IsTempGraphObject(graph.gameObject)) { var prefab = uNodeEditorUtility.GetGameObjectSource(graph.gameObject, null); if (prefab != null) { var oriGraph = prefab.GetComponent <uNodeRoot>(); if (oriGraph != null) { var methods = ReflectionUtils.GetRuntimeType(oriGraph).GetMethods(); foreach (var m in methods) { if (m is RuntimeMethod && m.Name == name) { var parameters = m.GetParameters(); if (parameters.Length == paramTypes.Length) { if (runtime == null) { runtime = m as RuntimeMethod; } bool isValid = true; for (int i = 0; i < parameters.Length; i++) { if (parameters[i].ParameterType != paramTypes[i]) { isValid = false; break; } } if (isValid) { runtime = m as RuntimeMethod; } } } } } } } else { var methods = ReflectionUtils.GetRuntimeType(graph).GetMethods(); foreach (var m in methods) { if (m is RuntimeGraphMethod runtimeMethod && runtimeMethod.target == function) { runtime = runtimeMethod; break; } } } } MemberInfo nativeMember = null; if (graph.GeneratedTypeName.ToType(false) != null) { var type = graph.GeneratedTypeName.ToType(false); if (paramTypes.Length == 0 && function.GenericParameters.Count == 0) { nativeMember = type.GetMethod(name, MemberData.flags); } var members = type.GetMember(name, MemberData.flags); if (members != null) { var genericLength = function.GenericParameters.Count; foreach (var m in members) { if (m is MethodInfo method) { var mParam = method.GetParameters(); var mGeneric = method.GetGenericArguments(); if (paramTypes.Length == mParam.Length && mGeneric.Length == genericLength) { bool valid = true; for (int i = 0; i < mParam.Length; i++) { if (mParam[i].ParameterType != paramTypes[i]) { valid = false; break; } } if (valid) { nativeMember = method; break; } } } } } } var graphPrefabs = uNodeEditorUtility.FindPrefabsOfType <uNodeRoot>(); foreach (var prefab in graphPrefabs) { var gameObject = prefab; GameObject prefabContent = null; if (GraphUtility.HasTempGraphObject(prefab)) { gameObject = GraphUtility.GetTempGraphObject(prefab); } else if (uNodeEditorUtility.IsPrefab(prefab)) { prefabContent = PrefabUtility.LoadPrefabContents(AssetDatabase.GetAssetPath(prefab)); gameObject = prefabContent; } var scripts = gameObject.GetComponentsInChildren <MonoBehaviour>(true); bool hasUndo = false; Func <object, bool> scriptValidation = (obj) => { MemberData member = obj as MemberData; if (member != null && member.startType is RuntimeType) { var members = member.GetMembers(false); if (members != null) { for (int i = 0; i < members.Length; i++) { var m = members[i]; if (member.namePath.Length > i + 1) { if (m == runtime || m == nativeMember) { if (!hasUndo && prefabContent == null) { uNodeEditorUtility.RegisterFullHierarchyUndo(gameObject); hasUndo = true; } var path = member.namePath; path[i + 1] = function.Name; member.name = string.Join(".", path); { var items = member.Items; if (items.Length > i) { var mVal = MemberData.CreateFromMember(runtime); items[i] = mVal.Items[0]; member.SetItems(items); } } if (m == nativeMember) { referencedGraphs.Add(prefab); } return(true); } } } } } return(false); }; if (runtime != null) { bool hasChanged = false; Array.ForEach(scripts, script => { bool flag = AnalizerUtility.AnalizeObject(script, scriptValidation); if (flag) { hasChanged = true; hasUndo = false; uNodeGUIUtility.GUIChanged(script); uNodeEditorUtility.MarkDirty(script); } }); if (hasChanged) { if (gameObject != prefab) { uNodeEditorUtility.RegisterFullHierarchyUndo(prefab); if (prefabContent == null) { //Save the temporary graph GraphUtility.AutoSaveGraph(gameObject); } else { //Save the prefab contents and unload it uNodeEditorUtility.SavePrefabAsset(gameObject, prefab); } } uNodeEditorUtility.MarkDirty(prefab); } } if (prefabContent != null) { PrefabUtility.UnloadPrefabContents(prefabContent); } } } uNodeEditorUtility.RegisterFullHierarchyUndo(graph.gameObject); graph.Refresh(); Func <object, bool> validation = delegate(object OBJ) { return(CallbackRefactorFunction(OBJ, function, name, paramTypes)); }; Array.ForEach(graph.nodes, item => AnalizerUtility.AnalizeObject(item, validation)); if (GraphUtility.IsTempGraphObject(graph.gameObject)) { var prefab = uNodeEditorUtility.GetGameObjectSource(graph.gameObject, null); uNodeEditorUtility.RegisterFullHierarchyUndo(prefab); GraphUtility.AutoSaveGraph(graph.gameObject); } uNodeEditor.ClearGraphCache(); uNodeEditor.window?.Refresh(true); DoCompileReferences(graph, referencedGraphs); }
public static void RefactorProperty(uNodeProperty property, string name) { name = uNodeUtility.AutoCorrectName(name); var graph = property.owner; bool hasVariable = false; if (graph.Properties != null && graph.Properties.Count > 0) { foreach (var V in graph.Properties) { if (V.Name == name) { hasVariable = true; break; } } } if (graph.Variables != null && graph.Variables.Count > 0) { foreach (var V in graph.Variables) { if (V.Name == name) { hasVariable = true; break; } } } if (hasVariable) { return; } Undo.SetCurrentGroupName("Rename Property: " + property.Name); HashSet <GameObject> referencedGraphs = new HashSet <GameObject>(); if (graph != null) { RuntimeProperty runtime = null; if (graph is IIndependentGraph) { if (GraphUtility.IsTempGraphObject(graph.gameObject)) { var prefab = uNodeEditorUtility.GetGameObjectSource(graph.gameObject, null); if (prefab != null) { var oriGraph = prefab.GetComponent <uNodeRoot>(); if (oriGraph != null) { runtime = ReflectionUtils.GetRuntimeType(oriGraph).GetProperty(property.Name) as RuntimeProperty; } } } else { runtime = ReflectionUtils.GetRuntimeType(graph).GetProperty(property.Name) as RuntimeProperty; } } PropertyInfo nativeMember = null; if (graph.GeneratedTypeName.ToType(false) != null) { var type = graph.GeneratedTypeName.ToType(false); nativeMember = type.GetProperty(property.Name, MemberData.flags); } var graphPrefabs = uNodeEditorUtility.FindPrefabsOfType <uNodeRoot>(); foreach (var prefab in graphPrefabs) { var gameObject = prefab; GameObject prefabContent = null; if (GraphUtility.HasTempGraphObject(prefab)) { gameObject = GraphUtility.GetTempGraphObject(prefab); } else if (uNodeEditorUtility.IsPrefab(prefab)) { prefabContent = PrefabUtility.LoadPrefabContents(AssetDatabase.GetAssetPath(prefab)); gameObject = prefabContent; } var scripts = gameObject.GetComponentsInChildren <MonoBehaviour>(true); bool hasUndo = false; Func <object, bool> scriptValidation = (obj) => { MemberData member = obj as MemberData; if (member != null && member.startType is RuntimeType) { var members = member.GetMembers(false); if (members != null) { for (int i = 0; i < members.Length; i++) { var m = members[i]; if (member.namePath.Length > i + 1) { if (m == runtime || m == nativeMember) { if (!hasUndo && prefabContent == null) { uNodeEditorUtility.RegisterFullHierarchyUndo(gameObject); hasUndo = true; } var path = member.namePath; path[i + 1] = name; member.name = string.Join(".", path); if (m == nativeMember) { referencedGraphs.Add(prefab); } return(true); } } } } } return(false); }; if (runtime != null || nativeMember != null) { bool hasChanged = false; Array.ForEach(scripts, script => { bool flag = AnalizerUtility.AnalizeObject(script, scriptValidation); if (flag) { hasChanged = true; hasUndo = false; uNodeGUIUtility.GUIChanged(script); uNodeEditorUtility.MarkDirty(script); } }); if (hasChanged) { if (gameObject != prefab) { uNodeEditorUtility.RegisterFullHierarchyUndo(prefab); if (prefabContent == null) { //Save the temporary graph GraphUtility.AutoSaveGraph(gameObject); } else { //Save the prefab contents and unload it uNodeEditorUtility.SavePrefabAsset(gameObject, prefab); } } uNodeEditorUtility.MarkDirty(prefab); } } if (prefabContent != null) { PrefabUtility.UnloadPrefabContents(prefabContent); } } } uNodeEditorUtility.RegisterFullHierarchyUndo(graph.gameObject); string oldVarName = property.Name; property.Name = name; graph.Refresh(); Func <object, bool> validation = delegate(object OBJ) { return(CallbackRenameProperty(OBJ, graph, property.name, oldVarName)); }; Array.ForEach(graph.nodes, item => AnalizerUtility.AnalizeObject(item, validation)); if (GraphUtility.IsTempGraphObject(graph.gameObject)) { var prefab = uNodeEditorUtility.GetGameObjectSource(graph.gameObject, null); uNodeEditorUtility.RegisterFullHierarchyUndo(prefab); GraphUtility.AutoSaveGraph(graph.gameObject); } uNodeEditor.ClearGraphCache(); uNodeEditor.window?.Refresh(true); DoCompileReferences(graph, referencedGraphs); }
public static void RefactorVariable(VariableData variable, string name, UnityEngine.Object owner) { bool isLocal = false; uNodeRoot graph = owner as uNodeRoot; if (graph == null) { INode <uNodeRoot> node = owner as INode <uNodeRoot>; if (node != null) { graph = node.GetOwner(); isLocal = true; } } if (graph != null) { HashSet <GameObject> referencedGraphs = new HashSet <GameObject>(); if (!isLocal) { RuntimeField field = null; if (graph is IIndependentGraph) { if (GraphUtility.IsTempGraphObject(graph.gameObject)) { var prefab = uNodeEditorUtility.GetGameObjectSource(graph.gameObject, null); if (prefab != null) { var oriGraph = prefab.GetComponent <uNodeRoot>(); if (oriGraph != null) { field = ReflectionUtils.GetRuntimeType(oriGraph).GetField(variable.Name) as RuntimeField; } } } else { field = ReflectionUtils.GetRuntimeType(graph).GetField(variable.Name) as RuntimeField; } } FieldInfo nativeMember = null; if (graph.GeneratedTypeName.ToType(false) != null) { var type = graph.GeneratedTypeName.ToType(false); nativeMember = type.GetField(variable.Name, MemberData.flags); } var graphPrefabs = uNodeEditorUtility.FindPrefabsOfType <uNodeRoot>(); foreach (var prefab in graphPrefabs) { var gameObject = prefab; GameObject prefabContent = null; if (GraphUtility.HasTempGraphObject(prefab)) { gameObject = GraphUtility.GetTempGraphObject(prefab); } else if (uNodeEditorUtility.IsPrefab(prefab)) { prefabContent = PrefabUtility.LoadPrefabContents(AssetDatabase.GetAssetPath(prefab)); gameObject = prefabContent; } var scripts = gameObject.GetComponentsInChildren <MonoBehaviour>(true); bool hasUndo = false; Func <object, bool> scriptValidation = (obj) => { MemberData member = obj as MemberData; if (member != null) { var members = member.GetMembers(false); if (members != null) { for (int i = 0; i < members.Length; i++) { var m = members[i]; if (member.namePath.Length > i + 1) { if (m == field || m == nativeMember) { if (!hasUndo && prefabContent == null) { uNodeEditorUtility.RegisterFullHierarchyUndo(gameObject, "Rename Variable: " + variable.Name); hasUndo = true; } var path = member.namePath; path[i + 1] = name; member.name = string.Join(".", path); if (m == nativeMember) { referencedGraphs.Add(prefab); } return(true); } } } } } return(false); }; if (field != null || nativeMember != null) { bool hasChanged = false; Array.ForEach(scripts, script => { bool flag = AnalizerUtility.AnalizeObject(script, scriptValidation); if (flag) { hasChanged = true; hasUndo = false; uNodeGUIUtility.GUIChanged(script); uNodeEditorUtility.MarkDirty(script); } }); if (hasChanged) { if (gameObject != prefab) { uNodeEditorUtility.RegisterFullHierarchyUndo(prefab, "Rename Variable: " + variable.Name); if (prefabContent == null) { //Save the temporary graph GraphUtility.AutoSaveGraph(gameObject); } else { //Save the prefab contents uNodeEditorUtility.SavePrefabAsset(gameObject, prefab); } } uNodeEditorUtility.MarkDirty(prefab); } } if (prefabContent != null) { PrefabUtility.UnloadPrefabContents(prefabContent); } } } string oldVarName = variable.Name; variable.Name = name; Func <object, bool> validation = delegate(object OBJ) { return(CallbackRenameVariable(OBJ, owner, variable.Name, oldVarName)); }; graph.Refresh(); Array.ForEach(graph.nodes, item => AnalizerUtility.AnalizeObject(item, validation)); if (GraphUtility.IsTempGraphObject(graph.gameObject)) { var prefab = uNodeEditorUtility.GetGameObjectSource(graph.gameObject, null); uNodeEditorUtility.RegisterFullHierarchyUndo(prefab, "Rename Variable: " + oldVarName); GraphUtility.AutoSaveGraph(graph.gameObject); } uNodeEditor.ClearGraphCache(); uNodeEditor.window?.Refresh(true); DoCompileReferences(graph, referencedGraphs); } }