using UnityEngine; using System; namespace DuloGames.UI { public static class UIUtility { /// /// Brings the game object to the front. /// /// Game Object. public static void BringToFront(GameObject go) { BringToFront(go, true); } /// /// Brings the game object to the front while specifing if re-parenting is allowed. /// /// The Game Object. /// Should we allow the method to change the Game Object's parent. public static void BringToFront(GameObject go, bool allowReparent) { Transform root = null; // Check if this game object is part of a UI Scene UIScene scene = UIUtility.FindInParents(go); // If the object has a parent ui scene if (scene != null && scene.content != null) { root = scene.content; } else { // Use canvas as root Canvas canvas = UIUtility.FindInParents(go); if (canvas != null) root = canvas.transform; } // If the object has a parent canvas if (allowReparent && root != null) go.transform.SetParent(root, true); // Set as last sibling go.transform.SetAsLastSibling(); // Handle the always on top components if (root != null) { UIAlwaysOnTop[] alwaysOnTopComponenets = root.gameObject.GetComponentsInChildren(); if (alwaysOnTopComponenets.Length > 0) { // Sort them by order Array.Sort(alwaysOnTopComponenets); foreach (UIAlwaysOnTop component in alwaysOnTopComponenets) { component.transform.SetAsLastSibling(); } } } } /// /// Finds the component in the game object's parents. /// /// The component. /// Game Object. /// The 1st type parameter. public static T FindInParents(GameObject go) where T : Component { if (go == null) return null; var comp = go.GetComponent(); if (comp != null) return comp; Transform t = go.transform.parent; while (t != null && comp == null) { comp = t.gameObject.GetComponent(); t = t.parent; } return comp; } } }