namespace SRF { using UnityEngine; public static class SRFGameObjectExtensions { public static T GetIComponent(this GameObject t) where T : class { return t.GetComponent(typeof (T)) as T; } /// /// Get the component T, or add it to the GameObject if none exists /// /// /// public static T GetComponentOrAdd(this GameObject obj) where T : Component { var t = obj.GetComponent(); if (t == null) { t = obj.AddComponent(); } return t; } /// /// Removed component of type T if it exists on the GameObject /// /// /// public static void RemoveComponentIfExists(this GameObject obj) where T : Component { var t = obj.GetComponent(); if (t != null) { Object.Destroy(t); } } /// /// Removed components of type T if it exists on the GameObject /// /// /// public static void RemoveComponentsIfExists(this GameObject obj) where T : Component { var t = obj.GetComponents(); for (var i = 0; i < t.Length; i++) { Object.Destroy(t[i]); } } /// /// Set enabled property MonoBehaviour of type T if it exists /// /// /// /// /// True if the component exists public static bool EnableComponentIfExists(this GameObject obj, bool enable = true) where T : MonoBehaviour { var t = obj.GetComponent(); if (t == null) { return false; } t.enabled = enable; return true; } /// /// Set the layer of a gameobject and all child objects /// /// /// public static void SetLayerRecursive(this GameObject o, int layer) { SetLayerInternal(o.transform, layer); } private static void SetLayerInternal(Transform t, int layer) { t.gameObject.layer = layer; foreach (Transform o in t) { SetLayerInternal(o, layer); } } } }