SRFGameObjectExtensions.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. using System;
  2. using System.Collections;
  3. using UnityEngine;
  4. namespace SRF
  5. {
  6. public static class SRFGameObjectExtensions
  7. {
  8. public static T GetIComponent<T>(this GameObject t) where T : class
  9. {
  10. return t.GetComponent(typeof(T)) as T;
  11. }
  12. public static T GetComponentOrAdd<T>(this GameObject obj) where T : Component
  13. {
  14. T t = obj.GetComponent<T>();
  15. if (t == null)
  16. {
  17. t = obj.AddComponent<T>();
  18. }
  19. return t;
  20. }
  21. public static void RemoveComponentIfExists<T>(this GameObject obj) where T : Component
  22. {
  23. T component = obj.GetComponent<T>();
  24. if (component != null)
  25. {
  26. UnityEngine.Object.Destroy(component);
  27. }
  28. }
  29. public static void RemoveComponentsIfExists<T>(this GameObject obj) where T : Component
  30. {
  31. T[] components = obj.GetComponents<T>();
  32. for (int i = 0; i < components.Length; i++)
  33. {
  34. UnityEngine.Object.Destroy(components[i]);
  35. }
  36. }
  37. public static bool EnableComponentIfExists<T>(this GameObject obj, bool enable = true) where T : MonoBehaviour
  38. {
  39. T component = obj.GetComponent<T>();
  40. if (component == null)
  41. {
  42. return false;
  43. }
  44. component.enabled = enable;
  45. return true;
  46. }
  47. public static void SetLayerRecursive(this GameObject o, int layer)
  48. {
  49. SRFGameObjectExtensions.SetLayerInternal(o.transform, layer);
  50. }
  51. private static void SetLayerInternal(Transform t, int layer)
  52. {
  53. t.gameObject.layer = layer;
  54. IEnumerator enumerator = t.GetEnumerator();
  55. try
  56. {
  57. while (enumerator.MoveNext())
  58. {
  59. object obj = enumerator.Current;
  60. Transform t2 = (Transform)obj;
  61. SRFGameObjectExtensions.SetLayerInternal(t2, layer);
  62. }
  63. }
  64. finally
  65. {
  66. IDisposable disposable;
  67. if ((disposable = (enumerator as IDisposable)) != null)
  68. {
  69. disposable.Dispose();
  70. }
  71. }
  72. }
  73. }
  74. }