扩展GameObject.Find(string)方法,支持寻找Hierarchy面板隐藏的物体,返回GameObject
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.SceneManagement;
public static class ExpendGameObjectFind
{
public static GameObject Find(string name)
{
GameObject tGo1 = GameObject.Find(name);
if (tGo1 != null)
{
return tGo1;
}
else
{
//name = "AAA/BB/CCC" topName = "AAA" childName = "BB/CCC"
string topName = name;
string childName = "";
if (name.IndexOf('/') != -1)
{
topName = name.Substring(0, name.IndexOf('/'));
childName = name.Substring(name.IndexOf('/') + 1);
}
Debug.Log("topName = " + topName);
Debug.Log("childName = " + childName);
Scene curScene = SceneManager.GetActiveScene();
if (curScene != null)
{
GameObject tGo = curScene.GetRootGameObjects().First(
go =>
{
if (go.name == topName)
{
return true;
}
else
{
return false;
}
}
);
if (tGo != null)
{
if (!string.IsNullOrEmpty(childName))
{
tGo = tGo.transform.Find(childName).gameObject;
}
Debug.Log("Find '" + name + "' [" + tGo.name + "]GameObject is exist!");
return tGo;
}
}
else
{
Debug.LogError("curScene is nil!");
}
Debug.LogWarning("'" + name + "' path is not exist!");
return null;
}
}
}