Editor编辑器扩展开发之2个常用遍历gameobject和判断预制体方法

网上转载

判断是否预制体

 /// 
    /// 获取预制体资源路径。
    /// 
    /// 
    /// 
    public string GetPrefabAssetPathAfter2017(GameObject gameObject)
    {
        /* Unity中一个预制体对象可能处于3种状态:
            位于Project中,是PrefabAsset;
            位于Scene中,是PrefabInstance;
            位于PrefabMode Scene中,既不是PrefabAsset也不是Prefab Instance。
         */
        // Project中的Prefab是Asset不是Instance
        if (UnityEditor.PrefabUtility.IsPartOfPrefabAsset(gameObject))
        {
            // 预制体资源就是自身
            return UnityEditor.AssetDatabase.GetAssetPath(gameObject);
        }

        // Scene中的Prefab Instance是Instance不是Asset
        if (UnityEditor.PrefabUtility.IsPartOfPrefabInstance(gameObject))
        {
            // 获取预制体资源
            var prefabAsset = PrefabUtility.GetCorrespondingObjectFromOriginalSource(gameObject);
            return UnityEditor.AssetDatabase.GetAssetPath(prefabAsset);
        }

        // PrefabMode中的GameObject既不是Instance也不是Asset
        var prefabStage = UnityEditor.Experimental.SceneManagement.PrefabStageUtility.GetPrefabStage(gameObject);
        if (prefabStage != null)
        {
            // 预制体资源:prefabAsset = prefabStage.prefabContentsRoot
            return prefabStage.prefabAssetPath;
        }

        // 不是预制体
        return null;
    }

遍历场景中所有GameObject

   /// 
    /// 方法 1:获取这个场景的所有对象
    /// 
    /// 
    List GetAllGo()
    {
        List allGOs = new List();
     //   GameObject[] rootGOs = gameObject.scene.GetRootGameObjects();
        GameObject[] rootGOs = SceneManager.GetActiveScene().GetRootGameObjects();
 
        for (int i = 0; i < rootGOs.Length; i++)
            GetAllChildren(rootGOs[i].transform, allGOs);
        return allGOs;
    }
    void GetAllChildren(Transform current, List arrayToFill)
    {
        arrayToFill.Add(current.gameObject);
 
        for (int i = 0; i < current.childCount; i++)
            GetAllChildren(current.GetChild(i), arrayToFill);
    }
    //方法 2
    private List GetAllSceneObjectsWithInactive()
    {
        var allTransforms = Resources.FindObjectsOfTypeAll(typeof(Transform));
        var previousSelection = Selection.objects;
        Selection.objects = allTransforms.Cast()
            .Where(x => x != null)
            .Select(x => x.gameObject)
            .Where(x => x != null && !x.activeInHierarchy)
            .Cast().ToArray();
 
        var selectedTransforms = Selection.GetTransforms(SelectionMode.Editable | SelectionMode.ExcludePrefab);
        Selection.objects = previousSelection;
 
        return selectedTransforms.Select(tr => tr.gameObject).ToList();
    }

你可能感兴趣的:(每天一点u3d)