Unity获取场景gameobject的路径

在使用Unity时,我们有时候写代码需要获取某个子物体下gameobject的路径,如果只是一俩个层级还好说,自己用键盘敲就可以了,但是如果层级变多的情况下,就显得麻烦多多。下面提供一个插件,可也通过直接将gameobject的路径复制到剪切板当中:

1:将字符串拷贝到剪切板当中:

    /// <summary>
    /// 剪切板
    /// </summary>
    public class ClipBoard
    {
        /// <summary>
        /// 将信息复制到剪切板当中
        /// </summary>
        public static void Copy(string format,params object[] args)
        {
            string result = string.Format(format,args);
            TextEditor editor = new TextEditor();
            editor.content = new GUIContent( result);
            editor.OnFocus();
            editor.Copy();
        }
    }

2:获取场景gameobject的路径

        [MenuItem("LazerSelect/Copy/ObjectPath")]
        private static void CopyGameObjectPath()
        {
            UnityEngine.Object obj = Selection.activeObject;
            if (obj == null)
            {
                Debug.LogError("You must select Obj first!");
                return;
            }
            string result = AssetDatabase.GetAssetPath(obj);
            if (string.IsNullOrEmpty(result))//如果不是资源则在场景中查找
            {
                Transform selectChild = Selection.activeTransform;
                if (selectChild != null)
                {
                    result = selectChild.name;
                    while (selectChild.parent != null)
                    {
                        selectChild = selectChild.parent;
                        result = string.Format("{0}/{1}", selectChild.name, result);
                    }
                }
            }
            ClipBoard.Copy(result);
            Debug.Log(string.Format("The gameobject:{0}'s path has been copied to the clipboard!", obj.name));
        }

通过建立脚本,直接放到Editor文件夹下就可以了,然后再看编辑器就可以看到相关的按钮了

如果大伙仔细发现,这个方法还有一个功能就是也可以在场景中把某个资源,活文件夹的路径拷贝到剪切板当中呦,大伙可以尝试一下。

猜你喜欢

转载自blog.csdn.net/liulei199079/article/details/50750909