TargetList.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #if UNITY_EDITOR
  2. using UnityEngine;
  3. using UnityEditor;
  4. using System.Collections.Generic;
  5. namespace VLB
  6. {
  7. public class TargetList<T> : IEnumerable<T> where T : MonoBehaviour
  8. {
  9. public int Count { get { return m_Targets != null ? m_Targets.Count : 0; } }
  10. public T this[int key] { get { return m_Targets != null ? m_Targets[key] : null; } }
  11. public List<T> m_Targets = null;
  12. public TargetList(UnityEngine.Object[] entities)
  13. {
  14. m_Targets = new List<T>();
  15. foreach (var entity in entities)
  16. {
  17. if (entity is T)
  18. {
  19. m_Targets.Add(entity as T); // directly get the component from the object
  20. }
  21. else
  22. {
  23. // otherwise get access from the current MonoBehaviour, in case the current MonoBehaviour is not the type wanted as target
  24. var behaviour = entity as MonoBehaviour;
  25. var comp = behaviour.GetComponent<T>();
  26. if (comp)
  27. m_Targets.Add(comp);
  28. }
  29. }
  30. Debug.Assert(m_Targets.Count > 0);
  31. }
  32. public bool HasAtLeastOneTargetWith(System.Func<T, bool> lambda)
  33. {
  34. foreach (var target in m_Targets)
  35. {
  36. if (lambda(target))
  37. {
  38. return true;
  39. }
  40. }
  41. return false;
  42. }
  43. public void RecordUndoAction(string name, System.Action<T> lambda)
  44. {
  45. Undo.RecordObjects(m_Targets.ToArray(), name);
  46. foreach (var target in m_Targets)
  47. {
  48. lambda(target);
  49. }
  50. }
  51. // make this object foreach compatible
  52. public IEnumerator<T> GetEnumerator()
  53. {
  54. foreach (var target in m_Targets)
  55. yield return target;
  56. }
  57. System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
  58. {
  59. return this.GetEnumerator();
  60. }
  61. }
  62. }
  63. #endif