GameUI.cs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945
  1. using System.Collections.Generic;
  2. using UnityEngine;
  3. using UnityEngine.UIElements;
  4. using UnityEngine.InputSystem;
  5. public class GameUI : MonoBehaviour
  6. {
  7. [Header("UI Documents")]
  8. public UIDocument mainUIDocument;
  9. private VisualElement root;
  10. private Label woodLabel;
  11. private Label stoneLabel;
  12. private Label foodLabel;
  13. private Label timeSpeedLabel;
  14. private Button pauseButton;
  15. private Button speed1xButton;
  16. private Button speed2xButton;
  17. private Button speed10xButton;
  18. // Villager Panel
  19. private VisualElement villagerPanel;
  20. private Label villagerInfoLabel;
  21. private VisualElement jobButtonsContainer;
  22. private List<Button> jobButtons = new List<Button>();
  23. private Villager currentSelectedVillager; // Store reference to avoid deselection issues
  24. // Selected Object Panel
  25. private VisualElement selectionPanel;
  26. private Label selectionInfoLabel;
  27. // Build Menu
  28. private VisualElement buildMenuPanel;
  29. private Button buildMenuToggle;
  30. private VisualElement buildCategoriesContainer;
  31. private VisualElement buildItemsContainer;
  32. private Button livingCategoryButton;
  33. private Button workingCategoryButton;
  34. private Button decorativeCategoryButton;
  35. private Label buildModeStatusLabel;
  36. private bool isBuildMenuOpen = false;
  37. private BuildingCategory currentBuildCategory;
  38. // Housing System
  39. private Label housingStatusLabel;
  40. private Label housingWarningLabel;
  41. private BuildingSystem buildingSystem;
  42. private HousingManager housingManager;
  43. void Start()
  44. {
  45. StartCoroutine(InitializeWhenReady());
  46. }
  47. System.Collections.IEnumerator InitializeWhenReady()
  48. {
  49. // Wait for GameManager to be initialized
  50. while (GameManager.Instance == null)
  51. {
  52. yield return null;
  53. }
  54. Debug.Log("GameManager found, initializing UI...");
  55. InitializeUI();
  56. SubscribeToEvents();
  57. // Update initial UI state after a short delay to ensure everything is ready
  58. yield return StartCoroutine(DelayedUIUpdate());
  59. }
  60. System.Collections.IEnumerator DelayedUIUpdate()
  61. {
  62. // Wait a few frames to ensure everything is initialized
  63. yield return new WaitForEndOfFrame();
  64. yield return new WaitForEndOfFrame();
  65. Debug.Log("Performing delayed UI update...");
  66. UpdateAllUI();
  67. // Force update resource displays with current values
  68. if (GameManager.Instance?.resourceManager != null)
  69. {
  70. var resources = GameManager.Instance.resourceManager.GetAllResources();
  71. Debug.Log($"Current resources: Wood={resources.GetValueOrDefault(ResourceType.Wood, 0)}, Stone={resources.GetValueOrDefault(ResourceType.Stone, 0)}, Food={resources.GetValueOrDefault(ResourceType.Food, 0)}");
  72. // Force manual UI updates
  73. foreach (var kvp in resources)
  74. {
  75. UpdateResourceDisplay(kvp.Key, kvp.Value);
  76. }
  77. }
  78. }
  79. void InitializeUI()
  80. {
  81. if (mainUIDocument == null)
  82. {
  83. mainUIDocument = GetComponent<UIDocument>();
  84. }
  85. if (mainUIDocument == null)
  86. {
  87. Debug.LogError("UI Document is required for GameUI! Please assign it in the inspector.");
  88. return;
  89. }
  90. Debug.Log($"UI Document found: {mainUIDocument.name}");
  91. Debug.Log($"UI Document's visual tree asset: {(mainUIDocument.visualTreeAsset != null ? mainUIDocument.visualTreeAsset.name : "NULL")}");
  92. if (mainUIDocument.visualTreeAsset == null)
  93. {
  94. Debug.LogWarning("UIDocument has no Visual Tree Asset assigned. Trying to auto-load...");
  95. // Try to load the UXML file from Resources folder
  96. VisualTreeAsset uxml = Resources.Load<VisualTreeAsset>("GameUI");
  97. if (uxml == null)
  98. {
  99. // Try alternative paths
  100. uxml = Resources.Load<VisualTreeAsset>("UI/GameUI");
  101. }
  102. if (uxml == null)
  103. {
  104. Debug.Log("Trying to load with .uxml extension...");
  105. // Some versions need explicit extension
  106. uxml = Resources.Load<VisualTreeAsset>("GameUI.uxml");
  107. }
  108. if (uxml != null)
  109. {
  110. mainUIDocument.visualTreeAsset = uxml;
  111. Debug.Log($"Auto-loaded UXML asset: {uxml.name}");
  112. }
  113. else
  114. {
  115. Debug.LogError("Could not auto-load GameUI.uxml! Please assign it manually or move it to Resources folder.");
  116. AttemptAutoFixUIDocument();
  117. return;
  118. }
  119. }
  120. root = mainUIDocument.rootVisualElement;
  121. Debug.Log($"Root element found: {root != null}, children count: {root?.childCount ?? 0}");
  122. if (root != null && root.childCount == 0)
  123. {
  124. Debug.LogError($"Root element has no children! The UXML file '{mainUIDocument.visualTreeAsset.name}' may be empty or not loading properly.");
  125. return;
  126. }
  127. // Get resource labels
  128. woodLabel = root.Q<Label>("wood-amount");
  129. stoneLabel = root.Q<Label>("stone-amount");
  130. foodLabel = root.Q<Label>("food-amount");
  131. Debug.Log($"Resource UI found - Wood: {woodLabel != null}, Stone: {stoneLabel != null}, Food: {foodLabel != null}");
  132. // Get time controls
  133. timeSpeedLabel = root.Q<Label>("time-speed");
  134. pauseButton = root.Q<Button>("pause-button");
  135. speed1xButton = root.Q<Button>("speed-1x");
  136. speed2xButton = root.Q<Button>("speed-2x");
  137. speed10xButton = root.Q<Button>("speed-10x");
  138. Debug.Log($"Time UI found - Speed: {timeSpeedLabel != null}, Pause: {pauseButton != null}, 1x: {speed1xButton != null}, 2x: {speed2xButton != null}, 10x: {speed10xButton != null}");
  139. // Get villager panel
  140. villagerPanel = root.Q<VisualElement>("villager-panel");
  141. villagerInfoLabel = root.Q<Label>("villager-info");
  142. jobButtonsContainer = root.Q<VisualElement>("job-buttons");
  143. Debug.Log($"Villager UI found - Panel: {villagerPanel != null}, Info: {villagerInfoLabel != null}, Jobs: {jobButtonsContainer != null}");
  144. // Get selection panel
  145. selectionPanel = root.Q<VisualElement>("selection-panel");
  146. selectionInfoLabel = root.Q<Label>("selection-info");
  147. Debug.Log($"Selection UI found - Panel: {selectionPanel != null}, Info: {selectionInfoLabel != null}");
  148. // Get build menu elements
  149. buildMenuPanel = root.Q<VisualElement>("build-menu-panel");
  150. buildMenuToggle = root.Q<Button>("build-menu-toggle");
  151. buildCategoriesContainer = root.Q<VisualElement>("build-categories");
  152. buildItemsContainer = root.Q<VisualElement>("build-items-container");
  153. livingCategoryButton = root.Q<Button>("living-category");
  154. workingCategoryButton = root.Q<Button>("working-category");
  155. decorativeCategoryButton = root.Q<Button>("decorative-category");
  156. buildModeStatusLabel = root.Q<Label>("build-mode-status");
  157. Debug.Log($"Build Menu UI found - Panel: {buildMenuPanel != null}, Toggle: {buildMenuToggle != null}");
  158. // Get housing elements
  159. housingStatusLabel = root.Q<Label>("housing-status");
  160. housingWarningLabel = root.Q<Label>("housing-warning");
  161. Debug.Log($"Housing UI found - Status: {housingStatusLabel != null}, Warning: {housingWarningLabel != null}");
  162. // Set up button callbacks
  163. SetupButtons();
  164. // Create job buttons
  165. CreateJobButtons();
  166. // Debug: List all found UI elements
  167. Debug.Log($"UI Initialization Summary:");
  168. Debug.Log($" Resource Labels - Wood: {woodLabel != null}, Stone: {stoneLabel != null}, Food: {foodLabel != null}");
  169. Debug.Log($" Time Controls - Speed Label: {timeSpeedLabel != null}, Buttons: {pauseButton != null}");
  170. Debug.Log($" Villager Panel - Panel: {villagerPanel != null}, Info: {villagerInfoLabel != null}");
  171. Debug.Log($" Selection Panel - Panel: {selectionPanel != null}, Info: {selectionInfoLabel != null}");
  172. // If no elements found, try to auto-fix by loading the UXML file
  173. if (woodLabel == null && stoneLabel == null && foodLabel == null)
  174. {
  175. AttemptAutoFixUIDocument();
  176. }
  177. }
  178. void AttemptAutoFixUIDocument()
  179. {
  180. Debug.LogError("=== UI SETUP ISSUE DETECTED ===");
  181. Debug.LogError("The UIDocument has no Visual Tree Asset assigned or the UXML file is empty.");
  182. Debug.LogError("To fix this:");
  183. Debug.LogError("1. Select the GameManager GameObject in the scene");
  184. Debug.LogError("2. Look at the UIDocument component in the inspector");
  185. Debug.LogError("3. Assign the GameUI.uxml file to the 'Visual Tree Asset' field");
  186. Debug.LogError("4. The GameUI.uxml file should be located at Assets/UI/GameUI.uxml");
  187. Debug.LogError("================================");
  188. }
  189. void SetupButtons()
  190. {
  191. // Time control buttons
  192. if (pauseButton != null)
  193. {
  194. pauseButton.RegisterCallback<ClickEvent>(evt =>
  195. {
  196. if (GameManager.Instance != null)
  197. {
  198. GameManager.Instance.TogglePause();
  199. Debug.Log("Pause button clicked");
  200. }
  201. });
  202. }
  203. if (speed1xButton != null)
  204. {
  205. speed1xButton.RegisterCallback<ClickEvent>(evt =>
  206. {
  207. if (GameManager.Instance?.timeManager != null)
  208. {
  209. GameManager.Instance.timeManager.SetSpeed(0);
  210. Debug.Log("1x speed button clicked");
  211. }
  212. });
  213. }
  214. if (speed2xButton != null)
  215. {
  216. speed2xButton.RegisterCallback<ClickEvent>(evt =>
  217. {
  218. if (GameManager.Instance?.timeManager != null)
  219. {
  220. GameManager.Instance.timeManager.SetSpeed(1);
  221. Debug.Log("2x speed button clicked");
  222. }
  223. });
  224. }
  225. if (speed10xButton != null)
  226. {
  227. speed10xButton.RegisterCallback<ClickEvent>(evt =>
  228. {
  229. if (GameManager.Instance?.timeManager != null)
  230. {
  231. GameManager.Instance.timeManager.SetSpeed(2);
  232. Debug.Log("10x speed button clicked");
  233. }
  234. });
  235. }
  236. // Build menu toggle button
  237. if (buildMenuToggle != null)
  238. {
  239. buildMenuToggle.RegisterCallback<ClickEvent>(evt =>
  240. {
  241. ToggleBuildMenu();
  242. Debug.Log("Build menu toggle clicked");
  243. });
  244. }
  245. // Build category buttons
  246. if (livingCategoryButton != null)
  247. {
  248. livingCategoryButton.RegisterCallback<ClickEvent>(evt =>
  249. {
  250. ShowBuildCategory(BuildingCategory.Living);
  251. Debug.Log("Living category selected");
  252. });
  253. }
  254. if (workingCategoryButton != null)
  255. {
  256. workingCategoryButton.RegisterCallback<ClickEvent>(evt =>
  257. {
  258. ShowBuildCategory(BuildingCategory.Working);
  259. Debug.Log("Working category selected");
  260. });
  261. }
  262. if (decorativeCategoryButton != null)
  263. {
  264. decorativeCategoryButton.RegisterCallback<ClickEvent>(evt =>
  265. {
  266. ShowBuildCategory(BuildingCategory.Decorative);
  267. Debug.Log("Decorative category selected");
  268. });
  269. }
  270. }
  271. void CreateJobButtons()
  272. {
  273. if (jobButtonsContainer == null)
  274. {
  275. Debug.LogWarning("Job buttons container not found!");
  276. return;
  277. }
  278. // Clear existing buttons
  279. jobButtonsContainer.Clear();
  280. jobButtons.Clear();
  281. // Create job buttons (skip None job type)
  282. foreach (JobType job in System.Enum.GetValues(typeof(JobType)))
  283. {
  284. if (job == JobType.None) continue; // Skip "None" job
  285. Button jobButton = new Button();
  286. jobButton.text = GetJobDisplayName(job);
  287. jobButton.AddToClassList("job-button");
  288. jobButton.RegisterCallback<ClickEvent>(evt => AssignJobToSelectedVillager(job));
  289. // Initially disable all job buttons
  290. jobButton.SetEnabled(false);
  291. jobButtonsContainer.Add(jobButton);
  292. jobButtons.Add(jobButton);
  293. }
  294. Debug.Log($"Created {jobButtons.Count} job buttons (initially disabled)");
  295. }
  296. string GetJobDisplayName(JobType job)
  297. {
  298. return job switch
  299. {
  300. JobType.Woodcutter => "Woodcutter",
  301. JobType.Stonecutter => "Stonecutter",
  302. JobType.Farmer => "Farmer",
  303. JobType.Builder => "Builder",
  304. _ => job.ToString()
  305. };
  306. }
  307. void AssignJobToSelectedVillager(JobType job)
  308. {
  309. // Use stored reference instead of real-time selection to avoid deselection issues
  310. if (currentSelectedVillager == null)
  311. {
  312. Debug.Log("No villager stored for job assignment - this shouldn't happen if buttons are disabled properly");
  313. return;
  314. }
  315. if (GameManager.Instance?.villagerManager == null)
  316. {
  317. Debug.LogWarning("VillagerManager not found!");
  318. return;
  319. }
  320. Debug.Log($"Assigning job {job} to stored villager: {currentSelectedVillager.name}");
  321. // Find the closest available workplace for this job
  322. GameObject workplace = GameManager.Instance.villagerManager.FindWorkplaceForJob(job, currentSelectedVillager.transform.position);
  323. if (workplace != null)
  324. {
  325. // Assign villager to specific workplace
  326. GameManager.Instance.villagerManager.AssignVillagerToSpecificWorkplace(currentSelectedVillager, job, workplace);
  327. Debug.Log($"Assigned {currentSelectedVillager.name} to {job} at {workplace.name}");
  328. }
  329. else
  330. {
  331. // Fallback to general job assignment if no specific workplace found
  332. GameManager.Instance.villagerManager.AssignVillagerToJob(currentSelectedVillager, job);
  333. Debug.Log($"Assigned {currentSelectedVillager.name} to {job} (no specific workplace found)");
  334. }
  335. // Update the villager panel to show new job
  336. UpdateVillagerPanel(currentSelectedVillager);
  337. }
  338. void SubscribeToEvents()
  339. {
  340. // Subscribe to resource changes
  341. ResourceManager.OnResourceChanged += UpdateResourceDisplay;
  342. // Subscribe to time changes
  343. TimeManager.OnTimeSpeedChanged += UpdateTimeDisplay;
  344. TimeManager.OnPauseStateChanged += UpdatePauseDisplay;
  345. // Subscribe to villager selection
  346. Villager.OnVillagerSelected += UpdateVillagerPanel;
  347. // Subscribe to building system events
  348. BuildingSystem.OnBuildModeEntered += OnBuildModeEntered;
  349. BuildingSystem.OnBuildModeExited += OnBuildModeExited;
  350. // Subscribe to housing events
  351. HousingManager.OnHousingStatusChanged += UpdateHousingStatus;
  352. HousingManager.OnHousingWarning += ShowHousingWarning;
  353. // Get references to building system components
  354. buildingSystem = FindFirstObjectByType<BuildingSystem>();
  355. housingManager = FindFirstObjectByType<HousingManager>();
  356. if (buildingSystem == null)
  357. {
  358. Debug.LogWarning("BuildingSystem not found! Build menu will not work properly.");
  359. }
  360. if (housingManager == null)
  361. {
  362. Debug.LogWarning("HousingManager not found! Housing warnings will not work.");
  363. }
  364. }
  365. void OnDestroy()
  366. {
  367. // Unsubscribe from events
  368. ResourceManager.OnResourceChanged -= UpdateResourceDisplay;
  369. TimeManager.OnTimeSpeedChanged -= UpdateTimeDisplay;
  370. TimeManager.OnPauseStateChanged -= UpdatePauseDisplay;
  371. Villager.OnVillagerSelected -= UpdateVillagerPanel;
  372. // Unsubscribe from building system events
  373. BuildingSystem.OnBuildModeEntered -= OnBuildModeEntered;
  374. BuildingSystem.OnBuildModeExited -= OnBuildModeExited;
  375. // Unsubscribe from housing events
  376. HousingManager.OnHousingStatusChanged -= UpdateHousingStatus;
  377. HousingManager.OnHousingWarning -= ShowHousingWarning;
  378. }
  379. void UpdateAllUI()
  380. {
  381. // Update resource displays
  382. if (GameManager.Instance?.resourceManager != null)
  383. {
  384. var resources = GameManager.Instance.resourceManager.GetAllResources();
  385. foreach (var kvp in resources)
  386. {
  387. UpdateResourceDisplay(kvp.Key, kvp.Value);
  388. }
  389. }
  390. // Update time display
  391. if (GameManager.Instance?.timeManager != null)
  392. {
  393. UpdateTimeDisplay(GameManager.Instance.timeManager.CurrentTimeScale);
  394. UpdatePauseDisplay(GameManager.Instance.timeManager.IsPaused);
  395. }
  396. // Update selection
  397. UpdateSelectionPanel();
  398. }
  399. void UpdateResourceDisplay(ResourceType type, int amount)
  400. {
  401. Label targetLabel = null;
  402. string elementName = "";
  403. switch (type)
  404. {
  405. case ResourceType.Wood:
  406. targetLabel = woodLabel;
  407. elementName = "wood-amount";
  408. break;
  409. case ResourceType.Stone:
  410. targetLabel = stoneLabel;
  411. elementName = "stone-amount";
  412. break;
  413. case ResourceType.Food:
  414. targetLabel = foodLabel;
  415. elementName = "food-amount";
  416. break;
  417. }
  418. if (targetLabel != null)
  419. {
  420. targetLabel.text = amount.ToString();
  421. Debug.Log($"Updated {type} to {amount} successfully");
  422. }
  423. else
  424. {
  425. Debug.LogWarning($"Could not find UI label for {type} (looking for '{elementName}')");
  426. // Try to re-find the element
  427. if (root != null)
  428. {
  429. targetLabel = root.Q<Label>(elementName);
  430. if (targetLabel != null)
  431. {
  432. targetLabel.text = amount.ToString();
  433. Debug.Log($"Re-found and updated {type} to {amount}");
  434. // Update the cached reference
  435. switch (type)
  436. {
  437. case ResourceType.Wood: woodLabel = targetLabel; break;
  438. case ResourceType.Stone: stoneLabel = targetLabel; break;
  439. case ResourceType.Food: foodLabel = targetLabel; break;
  440. }
  441. }
  442. else
  443. {
  444. Debug.LogError($"Element '{elementName}' not found in UXML! Check that the UXML file contains an element with name='{elementName}'");
  445. }
  446. }
  447. }
  448. }
  449. void UpdateTimeDisplay(float timeScale)
  450. {
  451. if (timeSpeedLabel != null)
  452. {
  453. if (timeScale == 0f)
  454. {
  455. timeSpeedLabel.text = "Paused";
  456. }
  457. else if (timeScale == 1f)
  458. {
  459. timeSpeedLabel.text = "1x";
  460. }
  461. else if (timeScale == 2f)
  462. {
  463. timeSpeedLabel.text = "2x";
  464. }
  465. else if (timeScale == 10f)
  466. {
  467. timeSpeedLabel.text = "10x";
  468. }
  469. else
  470. {
  471. timeSpeedLabel.text = $"{timeScale}x";
  472. }
  473. Debug.Log($"Updated time speed to {timeSpeedLabel.text}");
  474. }
  475. else
  476. {
  477. Debug.LogWarning("Time speed label not found!");
  478. }
  479. }
  480. void UpdatePauseDisplay(bool isPaused)
  481. {
  482. if (pauseButton != null)
  483. {
  484. pauseButton.text = isPaused ? "Resume" : "Pause";
  485. Debug.Log($"Updated pause button to: {pauseButton.text}");
  486. }
  487. if (timeSpeedLabel != null && isPaused)
  488. {
  489. timeSpeedLabel.text = "Paused";
  490. }
  491. }
  492. public void UpdateVillagerPanel(Villager villager)
  493. {
  494. Debug.Log($"UpdateVillagerPanel called for: {(villager != null ? villager.name : "null")}");
  495. // Store the villager reference for job assignment
  496. currentSelectedVillager = villager;
  497. Debug.Log($"Stored villager reference: {(currentSelectedVillager != null ? currentSelectedVillager.name : "null")}");
  498. if (villagerInfoLabel == null)
  499. {
  500. Debug.LogWarning("villagerInfoLabel is null - cannot show villager info");
  501. return;
  502. }
  503. // Update job button states
  504. UpdateJobButtonStates(villager);
  505. if (villager == null)
  506. {
  507. villagerInfoLabel.text = "No villager selected";
  508. Debug.Log("Updated villager panel: No villager selected");
  509. }
  510. else
  511. {
  512. string jobText = villager.currentJob == JobType.None ? "Unemployed" : GetJobDisplayName(villager.currentJob);
  513. string info = $"Name: {villager.name}\n" +
  514. $"Job: {jobText}\n" +
  515. $"Experience: {villager.experience.GetExperienceForJob(villager.currentJob):F1}\n" +
  516. $"State: {villager.state}";
  517. villagerInfoLabel.text = info;
  518. Debug.Log($"Updated villager panel with info: {info}");
  519. }
  520. }
  521. void UpdateJobButtonStates(Villager selectedVillager)
  522. {
  523. bool hasSelection = selectedVillager != null;
  524. // Enable/disable all job buttons based on villager selection
  525. foreach (var button in jobButtons)
  526. {
  527. button.SetEnabled(hasSelection);
  528. // Optional: Change button appearance based on villager's current job
  529. if (hasSelection)
  530. {
  531. string buttonJobName = button.text;
  532. string currentJobName = GetJobDisplayName(selectedVillager.currentJob);
  533. if (buttonJobName == currentJobName)
  534. {
  535. button.AddToClassList("current-job"); // You can style this in USS
  536. }
  537. else
  538. {
  539. button.RemoveFromClassList("current-job");
  540. }
  541. }
  542. }
  543. Debug.Log($"Job buttons {(hasSelection ? "enabled" : "disabled")} - {jobButtons.Count} buttons updated");
  544. }
  545. // Public method to manually refresh all UI elements
  546. public void ManualUIRefresh()
  547. {
  548. Debug.Log("Manual UI refresh requested");
  549. // Re-find all UI elements
  550. if (root != null)
  551. {
  552. woodLabel = root.Q<Label>("wood-amount");
  553. stoneLabel = root.Q<Label>("stone-amount");
  554. foodLabel = root.Q<Label>("food-amount");
  555. villagerInfoLabel = root.Q<Label>("villager-info");
  556. selectionInfoLabel = root.Q<Label>("selection-info");
  557. Debug.Log($"Re-found UI elements - Wood: {woodLabel != null}, Stone: {stoneLabel != null}, Food: {foodLabel != null}, VillagerInfo: {villagerInfoLabel != null}");
  558. // Force update all displays
  559. UpdateAllUI();
  560. }
  561. }
  562. void Update()
  563. {
  564. // Check for debug key to manually refresh UI
  565. if (Keyboard.current != null && Keyboard.current.f5Key.wasPressedThisFrame)
  566. {
  567. Debug.Log("F5 pressed - Manual UI refresh");
  568. ManualUIRefresh();
  569. }
  570. }
  571. void UpdateSelectionPanel()
  572. {
  573. if (selectionInfoLabel == null) return;
  574. var selectedObject = GameManager.Instance?.selectionManager?.SelectedObject;
  575. var selectedVillager = GameManager.Instance?.selectionManager?.SelectedVillager;
  576. if (selectedObject == null && selectedVillager == null)
  577. {
  578. selectionInfoLabel.text = "Nothing selected";
  579. return;
  580. }
  581. string info = "";
  582. if (selectedVillager != null)
  583. {
  584. info = $"Selected: {selectedVillager.name}";
  585. }
  586. else if (selectedObject != null)
  587. {
  588. // Add specific info based on object type
  589. Building building = selectedObject.GetComponent<Building>();
  590. if (building != null)
  591. {
  592. info = building.GetBuildingInfo();
  593. }
  594. else
  595. {
  596. ResourceNode node = selectedObject.GetComponent<ResourceNode>();
  597. if (node != null)
  598. {
  599. info = node.GetNodeInfo();
  600. }
  601. else
  602. {
  603. info = "Selected: " + selectedObject.name;
  604. }
  605. }
  606. }
  607. selectionInfoLabel.text = info;
  608. }
  609. // Build Menu Methods
  610. void ToggleBuildMenu()
  611. {
  612. // Verify UI references first
  613. VerifyBuildMenuReferences();
  614. isBuildMenuOpen = !isBuildMenuOpen;
  615. Debug.Log($"ToggleBuildMenu called - Menu is now {(isBuildMenuOpen ? "OPEN" : "CLOSED")}");
  616. // Show/hide the entire build menu panel
  617. if (buildMenuPanel != null)
  618. {
  619. buildMenuPanel.style.display = isBuildMenuOpen ? DisplayStyle.Flex : DisplayStyle.None;
  620. Debug.Log($"Build menu panel visibility set to: {(isBuildMenuOpen ? "Flex" : "None")}");
  621. }
  622. else
  623. {
  624. Debug.LogWarning("buildMenuPanel is null!");
  625. }
  626. if (buildCategoriesContainer != null)
  627. {
  628. buildCategoriesContainer.style.display = isBuildMenuOpen ? DisplayStyle.Flex : DisplayStyle.None;
  629. }
  630. if (buildMenuToggle != null)
  631. {
  632. buildMenuToggle.text = isBuildMenuOpen ? "Close Build Menu" : "Open Build Menu";
  633. Debug.Log($"Build menu toggle text updated to: {buildMenuToggle.text}");
  634. }
  635. else
  636. {
  637. Debug.LogWarning("buildMenuToggle is null!");
  638. }
  639. // Hide build items when closing menu
  640. if (!isBuildMenuOpen && buildItemsContainer != null)
  641. {
  642. buildItemsContainer.style.display = DisplayStyle.None;
  643. }
  644. Debug.Log($"Build menu {(isBuildMenuOpen ? "opened" : "closed")}");
  645. }
  646. void VerifyBuildMenuReferences()
  647. {
  648. if (root == null)
  649. {
  650. Debug.LogError("Root UI element is null!");
  651. return;
  652. }
  653. if (buildMenuPanel == null)
  654. {
  655. buildMenuPanel = root.Q<VisualElement>("build-menu-panel");
  656. Debug.Log($"Re-found buildMenuPanel: {buildMenuPanel != null}");
  657. }
  658. if (buildMenuToggle == null)
  659. {
  660. buildMenuToggle = root.Q<Button>("build-menu-toggle");
  661. Debug.Log($"Re-found buildMenuToggle: {buildMenuToggle != null}");
  662. }
  663. if (buildCategoriesContainer == null)
  664. {
  665. buildCategoriesContainer = root.Q<VisualElement>("build-categories");
  666. Debug.Log($"Re-found buildCategoriesContainer: {buildCategoriesContainer != null}");
  667. }
  668. }
  669. void ShowBuildCategory(BuildingCategory category)
  670. {
  671. if (buildingSystem == null)
  672. {
  673. Debug.LogWarning("BuildingSystem not found!");
  674. return;
  675. }
  676. currentBuildCategory = category;
  677. // Show build items container
  678. if (buildItemsContainer != null)
  679. {
  680. buildItemsContainer.style.display = DisplayStyle.Flex;
  681. // Clear existing items
  682. buildItemsContainer.Clear();
  683. // Get buildings for this category
  684. var buildings = buildingSystem.GetBuildingsByCategory(category);
  685. foreach (var building in buildings)
  686. {
  687. CreateBuildingButton(building);
  688. }
  689. Debug.Log($"Showing {buildings.Count} buildings for category: {category}");
  690. }
  691. }
  692. void CreateBuildingButton(BuildingTemplate template)
  693. {
  694. Button buildButton = new Button();
  695. buildButton.text = $"{template.name}\n{buildingSystem.GetResourceCostString(template)}";
  696. buildButton.AddToClassList("build-item-button");
  697. // Check if we can afford this building
  698. bool canAfford = CanAffordBuilding(template);
  699. buildButton.SetEnabled(canAfford);
  700. buildButton.RegisterCallback<ClickEvent>(evt =>
  701. {
  702. Debug.Log($"Selected building to build: {template.name}");
  703. buildingSystem.EnterBuildMode(template);
  704. // Don't close menu immediately - let it close when build mode exits
  705. });
  706. buildItemsContainer.Add(buildButton);
  707. }
  708. bool CanAffordBuilding(BuildingTemplate template)
  709. {
  710. if (GameManager.Instance?.resourceManager == null) return false;
  711. foreach (var cost in template.costs)
  712. {
  713. if (!GameManager.Instance.resourceManager.HasResource(cost.resourceType, cost.amount))
  714. {
  715. return false;
  716. }
  717. }
  718. return true;
  719. }
  720. void OnBuildModeEntered()
  721. {
  722. if (buildModeStatusLabel != null)
  723. {
  724. buildModeStatusLabel.text = "Build Mode Active - Left click to place, Right click or ESC to cancel";
  725. buildModeStatusLabel.style.display = DisplayStyle.Flex;
  726. }
  727. }
  728. void OnBuildModeExited()
  729. {
  730. if (buildModeStatusLabel != null)
  731. {
  732. buildModeStatusLabel.text = "";
  733. buildModeStatusLabel.style.display = DisplayStyle.None;
  734. }
  735. // Keep build menu open if it was open
  736. if (isBuildMenuOpen)
  737. {
  738. if (buildMenuPanel != null)
  739. {
  740. buildMenuPanel.style.display = DisplayStyle.Flex;
  741. Debug.Log("Build menu panel visibility preserved as Flex");
  742. }
  743. if (buildCategoriesContainer != null)
  744. {
  745. buildCategoriesContainer.style.display = DisplayStyle.Flex;
  746. }
  747. if (buildMenuToggle != null)
  748. {
  749. buildMenuToggle.text = "Close Build Menu";
  750. }
  751. }
  752. Debug.Log($"Build mode exited - UI status cleared, build menu state: {(isBuildMenuOpen ? "OPEN" : "CLOSED")}");
  753. }
  754. // Public method to force build menu visibility check
  755. public void EnsureBuildMenuAccessible()
  756. {
  757. VerifyBuildMenuReferences();
  758. if (buildMenuToggle != null)
  759. {
  760. buildMenuToggle.style.display = DisplayStyle.Flex;
  761. Debug.Log("Ensured build menu toggle is visible");
  762. }
  763. // If menu was supposed to be open, make sure it's visible
  764. if (isBuildMenuOpen && buildMenuPanel != null)
  765. {
  766. buildMenuPanel.style.display = DisplayStyle.Flex;
  767. Debug.Log("Ensured build menu panel is visible");
  768. }
  769. }
  770. // Debug method to check build menu state
  771. [System.Diagnostics.Conditional("UNITY_EDITOR")]
  772. public void DebugBuildMenuState()
  773. {
  774. Debug.Log("=== BUILD MENU DEBUG INFO ===");
  775. Debug.Log($"isBuildMenuOpen: {isBuildMenuOpen}");
  776. Debug.Log($"buildMenuPanel: {(buildMenuPanel != null ? "FOUND" : "NULL")}");
  777. Debug.Log($"buildMenuToggle: {(buildMenuToggle != null ? "FOUND" : "NULL")}");
  778. Debug.Log($"buildCategoriesContainer: {(buildCategoriesContainer != null ? "FOUND" : "NULL")}");
  779. Debug.Log($"buildItemsContainer: {(buildItemsContainer != null ? "FOUND" : "NULL")}");
  780. if (buildMenuPanel != null)
  781. {
  782. Debug.Log($"buildMenuPanel display: {buildMenuPanel.style.display.value}");
  783. }
  784. if (buildMenuToggle != null)
  785. {
  786. Debug.Log($"buildMenuToggle display: {buildMenuToggle.style.display.value}");
  787. Debug.Log($"buildMenuToggle text: {buildMenuToggle.text}");
  788. }
  789. Debug.Log("=============================");
  790. }
  791. // Housing System Methods
  792. void UpdateHousingStatus(int housedVillagers, int totalVillagers)
  793. {
  794. if (housingStatusLabel != null)
  795. {
  796. housingStatusLabel.text = $"Housing: {housedVillagers}/{totalVillagers} villagers housed";
  797. }
  798. // Hide warning if housing is adequate
  799. if (housedVillagers >= totalVillagers && housingWarningLabel != null)
  800. {
  801. housingWarningLabel.style.display = DisplayStyle.None;
  802. }
  803. }
  804. void ShowHousingWarning(string warningMessage)
  805. {
  806. if (housingWarningLabel != null)
  807. {
  808. housingWarningLabel.text = warningMessage;
  809. housingWarningLabel.style.display = DisplayStyle.Flex;
  810. }
  811. }
  812. }