在工作过程中,经常需要通过A下面的子物体B
例如transA.Find("XXX");
而填入路径是很繁琐的事情, 手写相对路径很容易出现拼写错误,所以我写了这个工具, 用来计算相对路径,然后Ctrl+V到代码中就好了.可以节省一些手动计算路径的时间并且完全避免了拼写错误的问题.
using UnityEditor;
using UnityEngine;
public class GetRelativePath : EditorWindow {
static GameObject parent = null;
static GameObject child = null;
[UnityEditor.MenuItem("Tool/Get Relative Path")]
static void Init()
{
var window = EditorWindow.GetWindow<GetRelativePath>();
window.Show();
}
void OnGUI()
{
parent = EditorGUI.ObjectField(new Rect(3, 3, position.width - 6, 20), "Parent", parent, typeof(GameObject)) as GameObject;
EditorGUILayout.Space();
child = EditorGUI.ObjectField(new Rect(3, 23, position.width - 6, 20), "Child", child, typeof(GameObject)) as GameObject;
if (parent&&child)
{
if (GUI.Button(new Rect(3, 45, position.width - 6, 20), "Get Path"))
{
var childPath = GetGameObjectPath(child);
var parentPath = GetGameObjectPath(parent);
if (childPath.StartsWith(parentPath))
{
var relativePath = childPath.Remove(0, parentPath.Length + 1);
EditorGUIUtility.systemCopyBuffer = relativePath;
EditorUtility.DisplayDialog("成功", "已经复制到系统剪切板", "OK");
}
else
{
EditorUtility.DisplayDialog("失败", "两个Gameobject没有父子关系", "OK");
}
}
}
else
EditorGUI.LabelField(new Rect(3, 85, position.width - 6, 20), "Missing:", "Select an object first");
}
void OnInspectorUpdate()
{
Repaint();
}
public static string GetGameObjectPath(GameObject obj)
{
string path = obj.name;
while (obj.transform.parent != null)
{
obj = obj.transform.parent.gameObject;
path = obj.name + "/" + path;
}
return path;
}
}
网友评论