GameObjectExtensions.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. namespace SRF
  2. {
  3. using UnityEngine;
  4. public static class SRFGameObjectExtensions
  5. {
  6. public static T GetIComponent<T>(this GameObject t) where T : class
  7. {
  8. return t.GetComponent(typeof (T)) as T;
  9. }
  10. /// <summary>
  11. /// Get the component T, or add it to the GameObject if none exists
  12. /// </summary>
  13. /// <typeparam name="T"></typeparam>
  14. /// <returns></returns>
  15. public static T GetComponentOrAdd<T>(this GameObject obj) where T : Component
  16. {
  17. var t = obj.GetComponent<T>();
  18. if (t == null)
  19. {
  20. t = obj.AddComponent<T>();
  21. }
  22. return t;
  23. }
  24. /// <summary>
  25. /// Removed component of type T if it exists on the GameObject
  26. /// </summary>
  27. /// <typeparam name="T"></typeparam>
  28. /// <param name="obj"></param>
  29. public static void RemoveComponentIfExists<T>(this GameObject obj) where T : Component
  30. {
  31. var t = obj.GetComponent<T>();
  32. if (t != null)
  33. {
  34. Object.Destroy(t);
  35. }
  36. }
  37. /// <summary>
  38. /// Removed components of type T if it exists on the GameObject
  39. /// </summary>
  40. /// <typeparam name="T"></typeparam>
  41. /// <param name="obj"></param>
  42. public static void RemoveComponentsIfExists<T>(this GameObject obj) where T : Component
  43. {
  44. var t = obj.GetComponents<T>();
  45. for (var i = 0; i < t.Length; i++)
  46. {
  47. Object.Destroy(t[i]);
  48. }
  49. }
  50. /// <summary>
  51. /// Set enabled property MonoBehaviour of type T if it exists
  52. /// </summary>
  53. /// <typeparam name="T"></typeparam>
  54. /// <param name="obj"></param>
  55. /// <param name="enable"></param>
  56. /// <returns>True if the component exists</returns>
  57. public static bool EnableComponentIfExists<T>(this GameObject obj, bool enable = true) where T : MonoBehaviour
  58. {
  59. var t = obj.GetComponent<T>();
  60. if (t == null)
  61. {
  62. return false;
  63. }
  64. t.enabled = enable;
  65. return true;
  66. }
  67. /// <summary>
  68. /// Set the layer of a gameobject and all child objects
  69. /// </summary>
  70. /// <param name="o"></param>
  71. /// <param name="layer"></param>
  72. public static void SetLayerRecursive(this GameObject o, int layer)
  73. {
  74. SetLayerInternal(o.transform, layer);
  75. }
  76. private static void SetLayerInternal(Transform t, int layer)
  77. {
  78. t.gameObject.layer = layer;
  79. foreach (Transform o in t)
  80. {
  81. SetLayerInternal(o, layer);
  82. }
  83. }
  84. }
  85. }