Editor编辑器扩展开发之2个常用遍历gameobject和判断预制体方法
Posted avi9111
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Editor编辑器扩展开发之2个常用遍历gameobject和判断预制体方法相关的知识,希望对你有一定的参考价值。
网上转载
判断是否预制体
/// <summary>
/// 获取预制体资源路径。
/// </summary>
/// <param name="gameObject"></param>
/// <returns></returns>
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
/// <summary>
/// 方法 1:获取这个场景的所有对象
/// </summary>
/// <returns></returns>
List<GameObject> GetAllGo()
{
List<GameObject> allGOs = new List<GameObject>();
// 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<GameObject> arrayToFill)
{
arrayToFill.Add(current.gameObject);
for (int i = 0; i < current.childCount; i++)
GetAllChildren(current.GetChild(i), arrayToFill);
}
//方法 2
private List<GameObject> GetAllSceneObjectsWithInactive()
{
var allTransforms = Resources.FindObjectsOfTypeAll(typeof(Transform));
var previousSelection = Selection.objects;
Selection.objects = allTransforms.Cast<Transform>()
.Where(x => x != null)
.Select(x => x.gameObject)
.Where(x => x != null && !x.activeInHierarchy)
.Cast<UnityEngine.Object>().ToArray();
var selectedTransforms = Selection.GetTransforms(SelectionMode.Editable | SelectionMode.ExcludePrefab);
Selection.objects = previousSelection;
return selectedTransforms.Select(tr => tr.gameObject).ToList();
}
以上是关于Editor编辑器扩展开发之2个常用遍历gameobject和判断预制体方法的主要内容,如果未能解决你的问题,请参考以下文章
Unity Amplify Shader Editor-编辑器扩展开发Canvas框架
Unity记一次Amplify Shader Editor-编辑器扩展开发Canvas框架