using System;
using System.Collections.Generic;
using UnityEngine;
using Object = UnityEngine.Object;
namespace UnityUtils {
public static class TransformExtensions {
///
/// Retrieves all the children of a given Transform.
///
///
/// This method can be used with LINQ to perform operations on all child Transforms. For example,
/// you could use it to find all children with a specific tag, to disable all children, etc.
/// Transform implements IEnumerable and the GetEnumerator method which returns an IEnumerator of all its children.
///
/// The Transform to retrieve children from.
/// An IEnumerable<Transform> containing all the child Transforms of the parent.
public static IEnumerable Children(this Transform parent) {
foreach (Transform child in parent) {
yield return child;
}
}
///
/// Resets transform's position, scale and rotation
///
/// Transform to use
public static void Reset(this Transform transform) {
transform.position = Vector3.zero;
transform.localRotation = Quaternion.identity;
transform.localScale = Vector3.one;
}
///
/// Destroys all child game objects of the given transform.
///
/// The Transform whose child game objects are to be destroyed.
public static void DestroyChildren(this Transform parent) {
parent.ForEveryChild(child => Object.Destroy(child.gameObject));
}
///
/// Immediately destroys all child game objects of the given transform.
///
/// The Transform whose child game objects are to be immediately destroyed.
public static void DestroyChildrenImmediate(this Transform parent) {
parent.ForEveryChild(child => Object.DestroyImmediate(child.gameObject));
}
///
/// Enables all child game objects of the given transform.
///
/// The Transform whose child game objects are to be enabled.
public static void EnableChildren(this Transform parent) {
parent.ForEveryChild(child => child.gameObject.SetActive(true));
}
///
/// Disables all child game objects of the given transform.
///
/// The Transform whose child game objects are to be disabled.
public static void DisableChildren(this Transform parent) {
parent.ForEveryChild(child => child.gameObject.SetActive(false));
}
///
/// Executes a specified action for each child of a given transform.
///
/// The parent transform.
/// The action to be performed on each child.
///
/// This method iterates over all child transforms in reverse order and executes a given action on them.
/// The action is a delegate that takes a Transform as parameter.
///
public static void ForEveryChild(this Transform parent, System.Action action) {
for (var i = parent.childCount - 1; i >= 0; i--) {
action(parent.GetChild(i));
}
}
[Obsolete("Renamed to ForEveryChild")]
static void PerformActionOnChildren(this Transform parent, System.Action action) {
parent.ForEveryChild(action);
}
}
}