MapLegendUI.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. using UnityEngine;
  2. using UnityEngine.UIElements;
  3. public class MapLegendUI : MonoBehaviour
  4. {
  5. [Header("UI References")]
  6. public UIDocument uiDocument;
  7. public VisualTreeAsset legendTemplate;
  8. public StyleSheet legendStyleSheet;
  9. private VisualElement root;
  10. void Start()
  11. {
  12. SetupUI();
  13. }
  14. void SetupUI()
  15. {
  16. Debug.Log("SetupUI called");
  17. // Get the UI Document component
  18. if (uiDocument == null)
  19. uiDocument = GetComponent<UIDocument>();
  20. if (uiDocument == null)
  21. {
  22. Debug.LogError("UIDocument component not found on MapLegendUI GameObject!");
  23. return;
  24. }
  25. Debug.Log("UIDocument found");
  26. // Load the UXML template if not assigned
  27. if (legendTemplate == null)
  28. {
  29. // Try multiple paths to find the UXML file
  30. legendTemplate = Resources.Load<VisualTreeAsset>("UI/MapLegend");
  31. if (legendTemplate == null)
  32. {
  33. legendTemplate = Resources.Load<VisualTreeAsset>("MapLegend");
  34. if (legendTemplate == null)
  35. {
  36. Debug.LogError("MapLegend.uxml not found! Make sure it's in a Resources folder.");
  37. return;
  38. }
  39. }
  40. }
  41. Debug.Log("UXML template loaded");
  42. // Load the USS stylesheet if not assigned
  43. if (legendStyleSheet == null)
  44. {
  45. // Try multiple paths to find the USS file
  46. legendStyleSheet = Resources.Load<StyleSheet>("UI/MapLegend");
  47. if (legendStyleSheet == null)
  48. {
  49. legendStyleSheet = Resources.Load<StyleSheet>("MapLegend");
  50. if (legendStyleSheet == null)
  51. {
  52. Debug.LogWarning("MapLegend.uss not found - using default styling");
  53. }
  54. }
  55. }
  56. Debug.Log("USS stylesheet loaded");
  57. // Clone the template and add it to the document
  58. root = uiDocument.rootVisualElement;
  59. var legendElement = legendTemplate.Instantiate();
  60. Debug.Log("Template instantiated");
  61. // Add the stylesheet if available
  62. if (legendStyleSheet != null)
  63. {
  64. root.styleSheets.Add(legendStyleSheet);
  65. }
  66. // Add the legend to the root
  67. root.Add(legendElement);
  68. // Initialize legend as visible
  69. var legend = root.Q("MapLegend");
  70. if (legend != null)
  71. {
  72. legend.style.display = DisplayStyle.Flex;
  73. Debug.Log("Legend initialized as visible");
  74. }
  75. Debug.Log("Legend UI setup complete");
  76. }
  77. }