1. 程式人生 > >Unity獲取場景gameobject的路徑

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資料夾下就可以了,然後再看編輯器就可以看到相關的按鈕了

如果大夥仔細發現,這個方法還有一個功能就是也可以在場景中把某個資源,活資料夾的路徑拷貝到剪下板當中呦,大夥可以嘗試一下。