Skip to content

Commit 5bc1356

Browse files
committed
feat(Util): Add generic find object with tag
1 parent 8b47803 commit 5bc1356

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

Assets/JCSUnity/Scripts/Util/JCS_Util.cs

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1060,6 +1060,63 @@ public static UnityEngine.Object[] FindObjectsByType(System.Type type)
10601060
#endif
10611061
}
10621062

1063+
/// <summary>
1064+
/// Return a list of game object with the tag name.
1065+
///
1066+
/// This is CG intensive, please try not to use it too often.
1067+
/// </summary>
1068+
public static List<GameObject> FindGameObjectsWithTag(string tag)
1069+
{
1070+
List<GameObject> result = new();
1071+
1072+
JCS_Loop.Times(SceneManager.sceneCount, (count) =>
1073+
{
1074+
Scene scene = SceneManager.GetSceneAt(count);
1075+
1076+
List<GameObject> objs = FindGameObjectsWithTag(tag, scene);
1077+
1078+
result.AddRange(objs);
1079+
});
1080+
1081+
return result;
1082+
}
1083+
// Deal with specific scene.
1084+
public static List<GameObject> FindGameObjectsWithTag(string tag, Scene scene)
1085+
{
1086+
List<GameObject> result = new();
1087+
1088+
foreach (GameObject root in scene.GetRootGameObjects())
1089+
{
1090+
// Add root self.
1091+
if (root.tag == tag)
1092+
result.Add(root);
1093+
1094+
List<GameObject> objs = FindGameObjectsWithTag(tag, root);
1095+
1096+
result.AddRange(objs);
1097+
}
1098+
1099+
return result;
1100+
}
1101+
// Deal with specific GameObject.
1102+
public static List<GameObject> FindGameObjectsWithTag(string tag, GameObject go)
1103+
{
1104+
List<GameObject> result = new();
1105+
1106+
// Add children.
1107+
foreach (Transform child in go.transform)
1108+
{
1109+
if (child.tag == tag)
1110+
result.Add(child.gameObject);
1111+
1112+
List<GameObject> nested = FindGameObjectsWithTag(tag, child.gameObject);
1113+
1114+
result.AddRange(nested);
1115+
}
1116+
1117+
return result;
1118+
}
1119+
10631120
/// <summary>
10641121
/// Find all the objects that are clone in the scene by type.
10651122
/// </summary>

0 commit comments

Comments
 (0)