58 lines
2.2 KiB
C#
58 lines
2.2 KiB
C#
using UnityEngine;
|
|
|
|
namespace gay.lilyy.Common
|
|
{
|
|
public static class ComponentHelper
|
|
{
|
|
/// <summary>
|
|
/// Searches for a component in children of the root GameObject.
|
|
/// Returns null if no component is found.
|
|
/// Logs an error and returns null if multiple components are found.
|
|
/// </summary>
|
|
/// <typeparam name="T">The component type to search for</typeparam>
|
|
/// <param name="root">The root GameObject to search in</param>
|
|
/// <returns>The component if exactly one is found, null otherwise</returns>
|
|
public static T? GetComponentInChildrenWithError<T>(GameObject root) where T : Component
|
|
{
|
|
if (root == null) return null;
|
|
|
|
T[] components = root.GetComponentsInChildren<T>(true);
|
|
if (components.Length == 0)
|
|
{
|
|
return null;
|
|
}
|
|
if (components.Length > 1)
|
|
{
|
|
Debug.LogError($"Multiple {typeof(T).Name} components found in children of {root.name}. Only one is allowed.");
|
|
return null;
|
|
}
|
|
return components[0];
|
|
}
|
|
|
|
/// <summary>
|
|
/// Searches for a component in children of the root Transform.
|
|
/// Returns null if no component is found.
|
|
/// Logs an error and returns null if multiple components are found.
|
|
/// </summary>
|
|
/// <typeparam name="T">The component type to search for</typeparam>
|
|
/// <param name="root">The root Transform to search in</param>
|
|
/// <returns>The component if exactly one is found, null otherwise</returns>
|
|
public static T? GetComponentInChildrenWithError<T>(Transform root) where T : Component
|
|
{
|
|
if (root == null) return null;
|
|
|
|
T[] components = root.GetComponentsInChildren<T>(true);
|
|
if (components.Length == 0)
|
|
{
|
|
return null;
|
|
}
|
|
if (components.Length > 1)
|
|
{
|
|
Debug.LogError($"Multiple {typeof(T).Name} components found in children of {root.name}. Only one is allowed.");
|
|
return null;
|
|
}
|
|
return components[0];
|
|
}
|
|
}
|
|
}
|
|
|