MethodExtensionForUnity.cs 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. using UnityEngine;
  2. //Unity的一些扩展方法
  3. static public class MethodExtensionForUnity
  4. {
  5. /// <summary>
  6. /// Gets or add a component. Usage example:
  7. /// BoxCollider boxCollider = transform.GetOrAddComponent<BoxCollider>();
  8. /// </summary>
  9. static public T GetOrAddComponent<T>(this Component child, bool set_enable = false) where T : Component
  10. {
  11. T result = child.GetComponent<T>();
  12. if (result == null)
  13. {
  14. result = child.gameObject.AddComponent<T>();
  15. }
  16. var bcomp = result as Behaviour;
  17. if (set_enable)
  18. {
  19. if (bcomp != null) bcomp.enabled = true;
  20. }
  21. return result;
  22. }
  23. static public T GetOrAddComponent<T>(this GameObject go) where T : Component
  24. {
  25. T result = go.transform.GetComponent<T>();
  26. if (result == null)
  27. {
  28. result = go.AddComponent<T>();
  29. }
  30. var bcomp = result as Behaviour;
  31. if (bcomp != null) bcomp.enabled = true;
  32. return result;
  33. }
  34. public static void walk(this GameObject o, System.Action<GameObject> f)
  35. {
  36. f(o);
  37. int numChildren = o.transform.childCount;
  38. for (int i = 0; i < numChildren; ++i)
  39. {
  40. walk(o.transform.GetChild(i).gameObject, f);
  41. }
  42. }
  43. }