Newer
Older
TheVengeance-Project-IADE-Unity2D / Assets / Scripts / UI / UIHandler.cs
  1. using JetBrains.Annotations;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using TMPro;
  6. using UnityEngine;
  7. public class UIHandler : MonoBehaviour, IObserver
  8. {
  9. [Header("Observer Type: ")]
  10. [SerializeField] private NotificationType notificationType;
  11. [SerializeField] private List<Building> buildings = new List<Building>();
  12. private Dictionary<string, GameObject> goInstantiated = new Dictionary<string, GameObject>();
  13. private Canvas canvas;
  14. // Start is called before the first frame update
  15. void Start()
  16. {
  17. buildings = FindObjectsOfType<Building>().ToList();
  18. for(int i = 0; i < buildings.Count; i++)
  19. {
  20. buildings[i].AddObserver(this);
  21. }
  22. canvas = GetComponent<Canvas>();
  23. }
  24. // Update is called once per frame
  25. void Update()
  26. {
  27. }
  28. //Notify the observer
  29. public void OnNotify(ObserverNotification notification)
  30. {
  31. if (notification.NotificationType == notificationType)
  32. {
  33. if (notification.ContainsKey("UIObject"))
  34. {
  35. GameObject uiObj;
  36. string message;
  37. string objectID;
  38. if (notification.TryGetData("UIObject", out uiObj))
  39. {
  40. if (notification.TryGetData("Message", out message) && notification.TryGetData("ObjectID", out objectID))
  41. {
  42. // Instantiate the UI object and store it with the unique ID
  43. GameObject instance = Instantiate(uiObj, gameObject.transform);
  44. instance.GetComponent<TextMeshProUGUI>().text = message;
  45. goInstantiated[objectID] = instance;
  46. }
  47. else
  48. {
  49. Instantiate(uiObj, gameObject.transform);
  50. }
  51. }
  52. }
  53. else if (notification.ContainsKey("DestroyUI"))
  54. {
  55. string uniqueID = notification.GetData<string>("DestroyUI");
  56. if (goInstantiated.ContainsKey(uniqueID))
  57. {
  58. Destroy(goInstantiated[uniqueID]);
  59. goInstantiated.Remove(uniqueID);
  60. }
  61. }
  62. }
  63. }
  64. }