MapLegendUI.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. // Get the UI Document component
  17. if (uiDocument == null)
  18. uiDocument = GetComponent<UIDocument>();
  19. if (uiDocument == null)
  20. {
  21. Debug.LogError("UIDocument component not found on MapLegendUI GameObject!");
  22. return;
  23. }
  24. // Load the UXML template if not assigned
  25. if (legendTemplate == null)
  26. {
  27. // Try multiple paths to find the UXML file
  28. legendTemplate = Resources.Load<VisualTreeAsset>("UI/MapLegend");
  29. if (legendTemplate == null)
  30. {
  31. legendTemplate = Resources.Load<VisualTreeAsset>("MapLegend");
  32. if (legendTemplate == null)
  33. {
  34. Debug.LogError("MapLegend.uxml not found! Make sure it's in a Resources folder.");
  35. return;
  36. }
  37. }
  38. }
  39. // Load the USS stylesheet if not assigned
  40. if (legendStyleSheet == null)
  41. {
  42. // Try multiple paths to find the USS file
  43. legendStyleSheet = Resources.Load<StyleSheet>("UI/MapLegend");
  44. if (legendStyleSheet == null)
  45. {
  46. legendStyleSheet = Resources.Load<StyleSheet>("MapLegend");
  47. if (legendStyleSheet == null)
  48. {
  49. Debug.LogWarning("MapLegend.uss not found - using default styling");
  50. }
  51. }
  52. }
  53. // Clone the template and add it to the document
  54. root = uiDocument.rootVisualElement;
  55. var legendElement = legendTemplate.Instantiate();
  56. // Add the stylesheet if available
  57. if (legendStyleSheet != null)
  58. {
  59. root.styleSheets.Add(legendStyleSheet);
  60. }
  61. // Add the legend to the root
  62. root.Add(legendElement);
  63. // Initialize legend as visible
  64. var legend = root.Q("MapLegend");
  65. if (legend != null)
  66. {
  67. legend.style.display = DisplayStyle.Flex;
  68. }
  69. }
  70. }