allow components off root, but only allow one or error
This commit is contained in:
parent
a49d2d74e6
commit
1f779f9297
18 changed files with 133 additions and 12 deletions
58
Common/Runtime/ComponentHelper.cs
Normal file
58
Common/Runtime/ComponentHelper.cs
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
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];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
Add table
Add a link
Reference in a new issue