GameObjectExtension.cs 489 B

12345678910111213141516171819202122232425
  1. using System;
  2. using UnityEngine;
  3. public static class GameObjectExtension
  4. {
  5. public static T GetOrAddComponent<T>(this GameObject self) where T : Component
  6. {
  7. T t = self.GetComponent<T>();
  8. if (t == null)
  9. {
  10. t = self.AddComponent<T>();
  11. }
  12. return t;
  13. }
  14. public static T GetOrAddComponent<T>(this Component self) where T : Component
  15. {
  16. T component = self.GetComponent<T>();
  17. if (component == null)
  18. {
  19. component.gameObject.AddComponent<T>();
  20. }
  21. return component;
  22. }
  23. }