using System; using UnityEngine; namespace Framework.Support { /// Provides helper methods for dealing with game objects public static class GameObjectHelper { /// Looks up a child of the specified game object by its name /// Parent of which a child will be looked up /// Name of the child that will be lookd up /// The child, if found, or null if no child with that name existed public static GameObject GetChildByName(GameObject parent, string name) { Transform childTransform = parent.transform.Find(name); if(childTransform == null) { return null; } else { return childTransform.gameObject; } } /// Adds one game object as child to another /// Parent the child will be added to /// Game object that will become a child public static void SetAsChild(GameObject parent, GameObject child) { if(parent == null) { child.transform.SetParent(null, worldPositionStays: false); } else { child.transform.SetParent(parent.transform, worldPositionStays: false); } } /// Looks for a component in a game object and its parents /// Type of component that should be looked up /// Game object in which the component will be searched /// The component of the specified type, if found, or null public static T GetComponentInParents(GameObject gameObject) where T : MonoBehaviour { if(GameObjectHelper.IsNullOrDestroyed(gameObject)) { return null; } Transform current = gameObject.transform; while(current != null) { T component = current.GetComponent(); if(component != null) { return component; } current = current.parent; } return null; } /// Checks whether a game object is null or destroyed already /// Game object reference that will be checked /// True if the reference is null or the game object has been destroyed public static bool IsNullOrDestroyed(GameObject gameObject) { if(ReferenceEquals(gameObject, null)) { return true; } else { return (gameObject == null); // Wrapper call - could be slow } } } } // namespace Framework.Support