关键词:UnityEditor、可视化节点编辑、Unity编辑器自定义窗口工具
使用Newtonsoft.Json、UnityEditor相关接口实现
主要代码:Handles.DrawBezier(起点,终点,起点切线向量,终点切线向量,颜色,null, 线粗度) 绘制贝塞尔曲线
Handles.DrawAAPolyLine(线粗度,顶点1, 顶点2, ...) 根据线段点绘制不规则线段
GUI.Window(id, rect, DrawNodeWindow, 窗口标题);
void DrawNodeWindow(int id) 传入的id即GUI.Window第一个参数,一般传节点唯一标识ID。LinkObj类是节点类,里面有一个位置pos数据是存储该节点窗口位于编辑器的位置SerializableVector2类型是一个可被Json序列化的Vector2,不然无法被序列化。
using Newtonsoft.Json;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;
public class LinkObj
{
public int id;
public List<int> preList;
public List<int> nextList;
public SerializableVector2 pos;//位于编辑窗口的位置
public LinkObj(int _id, SerializableVector2 _pos)
{
id = _id;
pos = _pos;
preList = new List<int>();
nextList = new List<int>();
}
}
public static class PathConfig
{
public static string SaveJsonPath = Application.dataPath + "/MyGraphicsEditorDemo/Editor/LinkList.json";
}
public class MyGraphicsEditorWindow : EditorWindow
{
private Dictionary<int, LinkObj> linkObjDict = new Dictionary<int, LinkObj>();
private int tempAddId;
private Vector2 scrollViewPos;
private Dictionary<int, Rect> linkObjRectDict = new Dictionary<int, Rect>();
private LinkObj currentSelectLinkObj;
private Color defaultColor;
private Vector2 detailScrollViewPos;
private bool isLoaded;
[MenuItem("Tools/可视链结构编辑器")]
private static void ShowWindow()
{
Debug.Log("打开可视链结构编辑器");
var window = EditorWindow.GetWindow(typeof(MyGraphicsEditorWindow)) as MyGraphicsEditorWindow;
window.minSize = new Vector2(1280, 500);
window.Show(true);
window.isLoaded = false;
}
MyGraphicsEditorWindow()
{
this.titleContent = new GUIContent("可视链结构编辑器");
}
private void OnGUI()
{
defaultColor = GUI.color;
EditorGUILayout.BeginHorizontal(GUILayout.Width(position.width), GUILayout.Height(position.height));
{
//左面板(操作)
EditorGUILayout.BeginVertical(GUILayout.Width(80));
{
EditorGUILayout.BeginHorizontal();
{
if (GUILayout.Button("加载"))
{
//如果本地没有对应的json 文件,重新创建
if (File.Exists(PathConfig.SaveJsonPath))
{
string json = File.ReadAllText(PathConfig.SaveJsonPath);
linkObjDict = JsonConvert.DeserializeObject<Dictionary<int, LinkObj>>(json);
if (linkObjDict == null)
{
linkObjDict = new Dictionary<int, LinkObj>