ContainerTargetsView.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // MIT License
  2. // https://gitlab.com/ilnprj
  3. // Copyright (c) 2020 ilnprj
  4. using UnityEngine;
  5. using System.Collections.Generic;
  6. namespace RadarComponents
  7. {
  8. /// <summary>
  9. /// A container that accepts tasks from the manager and sends them to the spawn / pool manager
  10. /// </summary>
  11. public class ContainerTargetsView : MonoBehaviour
  12. {
  13. [Header("Current Targets View")]
  14. public List<BaseTargetView> Targets = new List<BaseTargetView>();
  15. [Header("Prefab View Item")]
  16. [SerializeField]
  17. private BaseTargetView prefabView = default;
  18. [Header("Spawn root")]
  19. [SerializeField]
  20. private Transform spawnRoot = default;
  21. private ITargetManager targetManager;
  22. private PlayerLocator locator;
  23. private PoolBaseTargetView pool;
  24. /// <summary>
  25. /// Initializing a container with View.Here we get all the targets from TargetManager and create their display on the compass
  26. /// </summary>
  27. /// <param name="inputTargetManager"></param>
  28. public void SetTargetManager(ITargetManager inputTargetManager)
  29. {
  30. locator = FindObjectOfType<PlayerLocator>();
  31. pool = gameObject.AddComponent<PoolBaseTargetView>();
  32. targetManager = inputTargetManager;
  33. targetManager.onAddTarget += onAddTarget;
  34. targetManager.onRemoveTarget += onRemoveTarget;
  35. if (targetManager.Targets.Count != 0)
  36. {
  37. foreach (var item in targetManager.Targets)
  38. {
  39. onAddTarget(item);
  40. }
  41. }
  42. }
  43. private void OnValidate()
  44. {
  45. if (prefabView == null || spawnRoot == null)
  46. {
  47. Debug.LogError("Please set prefab and root transform in inspector. GameObject -"+gameObject.name);
  48. }
  49. }
  50. private void OnDisable()
  51. {
  52. targetManager.onAddTarget -= onAddTarget;
  53. targetManager.onRemoveTarget -= onRemoveTarget;
  54. }
  55. private void onAddTarget(ITarget target)
  56. {
  57. BaseTargetView item = pool.GetNewView(prefabView, spawnRoot);
  58. RectTransform rect = spawnRoot.GetComponent<RectTransform>();
  59. item.transform.SetParent(spawnRoot);
  60. item.InitTargetView(target, locator.transform, rect);
  61. Targets.Add(item);
  62. }
  63. private void onRemoveTarget(ITarget target)
  64. {
  65. BaseTargetView item = Targets.Find(x => x.CurrentTarget.GetHashCode() == target.GetHashCode());
  66. pool.SetToPool(item);
  67. }
  68. }
  69. }