GameUI.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974
  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. // Update building button states when resources change
  423. UpdateBuildingButtonStates();
  424. }
  425. else
  426. {
  427. Debug.LogWarning($"Could not find UI label for {type} (looking for '{elementName}')");
  428. // Try to re-find the element
  429. if (root != null)
  430. {
  431. targetLabel = root.Q<Label>(elementName);
  432. if (targetLabel != null)
  433. {
  434. targetLabel.text = amount.ToString();
  435. Debug.Log($"Re-found and updated {type} to {amount}");
  436. // Update the cached reference
  437. switch (type)
  438. {
  439. case ResourceType.Wood: woodLabel = targetLabel; break;
  440. case ResourceType.Stone: stoneLabel = targetLabel; break;
  441. case ResourceType.Food: foodLabel = targetLabel; break;
  442. }
  443. }
  444. else
  445. {
  446. Debug.LogError($"Element '{elementName}' not found in UXML! Check that the UXML file contains an element with name='{elementName}'");
  447. }
  448. }
  449. }
  450. }
  451. void UpdateTimeDisplay(float timeScale)
  452. {
  453. if (timeSpeedLabel != null)
  454. {
  455. if (timeScale == 0f)
  456. {
  457. timeSpeedLabel.text = "Paused";
  458. }
  459. else if (timeScale == 1f)
  460. {
  461. timeSpeedLabel.text = "1x";
  462. }
  463. else if (timeScale == 2f)
  464. {
  465. timeSpeedLabel.text = "2x";
  466. }
  467. else if (timeScale == 10f)
  468. {
  469. timeSpeedLabel.text = "10x";
  470. }
  471. else
  472. {
  473. timeSpeedLabel.text = $"{timeScale}x";
  474. }
  475. Debug.Log($"Updated time speed to {timeSpeedLabel.text}");
  476. }
  477. else
  478. {
  479. Debug.LogWarning("Time speed label not found!");
  480. }
  481. }
  482. void UpdatePauseDisplay(bool isPaused)
  483. {
  484. if (pauseButton != null)
  485. {
  486. pauseButton.text = isPaused ? "Resume" : "Pause";
  487. Debug.Log($"Updated pause button to: {pauseButton.text}");
  488. }
  489. if (timeSpeedLabel != null && isPaused)
  490. {
  491. timeSpeedLabel.text = "Paused";
  492. }
  493. }
  494. public void UpdateVillagerPanel(Villager villager)
  495. {
  496. Debug.Log($"UpdateVillagerPanel called for: {(villager != null ? villager.name : "null")}");
  497. // Store the villager reference for job assignment
  498. currentSelectedVillager = villager;
  499. Debug.Log($"Stored villager reference: {(currentSelectedVillager != null ? currentSelectedVillager.name : "null")}");
  500. if (villagerInfoLabel == null)
  501. {
  502. Debug.LogWarning("villagerInfoLabel is null - cannot show villager info");
  503. return;
  504. }
  505. // Update job button states
  506. UpdateJobButtonStates(villager);
  507. if (villager == null)
  508. {
  509. villagerInfoLabel.text = "No villager selected";
  510. Debug.Log("Updated villager panel: No villager selected");
  511. }
  512. else
  513. {
  514. string jobText = villager.currentJob == JobType.None ? "Unemployed" : GetJobDisplayName(villager.currentJob);
  515. string info = $"Name: {villager.name}\n" +
  516. $"Job: {jobText}\n" +
  517. $"Experience: {villager.experience.GetExperienceForJob(villager.currentJob):F1}\n" +
  518. $"State: {villager.state}";
  519. villagerInfoLabel.text = info;
  520. Debug.Log($"Updated villager panel with info: {info}");
  521. }
  522. }
  523. void UpdateJobButtonStates(Villager selectedVillager)
  524. {
  525. bool hasSelection = selectedVillager != null;
  526. // Enable/disable all job buttons based on villager selection
  527. foreach (var button in jobButtons)
  528. {
  529. button.SetEnabled(hasSelection);
  530. // Optional: Change button appearance based on villager's current job
  531. if (hasSelection)
  532. {
  533. string buttonJobName = button.text;
  534. string currentJobName = GetJobDisplayName(selectedVillager.currentJob);
  535. if (buttonJobName == currentJobName)
  536. {
  537. button.AddToClassList("current-job"); // You can style this in USS
  538. }
  539. else
  540. {
  541. button.RemoveFromClassList("current-job");
  542. }
  543. }
  544. }
  545. Debug.Log($"Job buttons {(hasSelection ? "enabled" : "disabled")} - {jobButtons.Count} buttons updated");
  546. }
  547. // Public method to manually refresh all UI elements
  548. public void ManualUIRefresh()
  549. {
  550. Debug.Log("Manual UI refresh requested");
  551. // Re-find all UI elements
  552. if (root != null)
  553. {
  554. woodLabel = root.Q<Label>("wood-amount");
  555. stoneLabel = root.Q<Label>("stone-amount");
  556. foodLabel = root.Q<Label>("food-amount");
  557. villagerInfoLabel = root.Q<Label>("villager-info");
  558. selectionInfoLabel = root.Q<Label>("selection-info");
  559. Debug.Log($"Re-found UI elements - Wood: {woodLabel != null}, Stone: {stoneLabel != null}, Food: {foodLabel != null}, VillagerInfo: {villagerInfoLabel != null}");
  560. // Force update all displays
  561. UpdateAllUI();
  562. }
  563. }
  564. void Update()
  565. {
  566. // Check for debug key to manually refresh UI
  567. if (Keyboard.current != null && Keyboard.current.f5Key.wasPressedThisFrame)
  568. {
  569. Debug.Log("F5 pressed - Manual UI refresh");
  570. ManualUIRefresh();
  571. }
  572. }
  573. void UpdateSelectionPanel()
  574. {
  575. if (selectionInfoLabel == null) return;
  576. var selectedObject = GameManager.Instance?.selectionManager?.SelectedObject;
  577. var selectedVillager = GameManager.Instance?.selectionManager?.SelectedVillager;
  578. if (selectedObject == null && selectedVillager == null)
  579. {
  580. selectionInfoLabel.text = "Nothing selected";
  581. return;
  582. }
  583. string info = "";
  584. if (selectedVillager != null)
  585. {
  586. info = $"Selected: {selectedVillager.name}";
  587. }
  588. else if (selectedObject != null)
  589. {
  590. // Add specific info based on object type
  591. Building building = selectedObject.GetComponent<Building>();
  592. if (building != null)
  593. {
  594. info = building.GetBuildingInfo();
  595. }
  596. else
  597. {
  598. ResourceNode node = selectedObject.GetComponent<ResourceNode>();
  599. if (node != null)
  600. {
  601. info = node.GetNodeInfo();
  602. }
  603. else
  604. {
  605. info = "Selected: " + selectedObject.name;
  606. }
  607. }
  608. }
  609. selectionInfoLabel.text = info;
  610. }
  611. // Build Menu Methods
  612. void ToggleBuildMenu()
  613. {
  614. // Verify UI references first
  615. VerifyBuildMenuReferences();
  616. isBuildMenuOpen = !isBuildMenuOpen;
  617. Debug.Log($"ToggleBuildMenu called - Menu is now {(isBuildMenuOpen ? "OPEN" : "CLOSED")}");
  618. // Show/hide only the build menu categories, not the entire panel (to keep toggle visible)
  619. if (buildCategoriesContainer != null)
  620. {
  621. buildCategoriesContainer.style.display = isBuildMenuOpen ? DisplayStyle.Flex : DisplayStyle.None;
  622. Debug.Log($"Build menu categories visibility set to: {(isBuildMenuOpen ? "Flex" : "None")}");
  623. }
  624. else
  625. {
  626. Debug.LogWarning("buildCategoriesContainer is null!");
  627. }
  628. // Ensure the build menu panel itself is always visible (contains the toggle button)
  629. if (buildMenuPanel != null)
  630. {
  631. buildMenuPanel.style.display = DisplayStyle.Flex;
  632. }
  633. if (buildMenuToggle != null)
  634. {
  635. buildMenuToggle.text = isBuildMenuOpen ? "Close Build Menu" : "Open Build Menu";
  636. // Ensure the toggle button itself is always visible
  637. buildMenuToggle.style.display = DisplayStyle.Flex;
  638. Debug.Log($"Build menu toggle text updated to: {buildMenuToggle.text}");
  639. }
  640. else
  641. {
  642. Debug.LogWarning("buildMenuToggle is null!");
  643. }
  644. // Hide build items when closing menu
  645. if (!isBuildMenuOpen && buildItemsContainer != null)
  646. {
  647. buildItemsContainer.style.display = DisplayStyle.None;
  648. }
  649. Debug.Log($"Build menu {(isBuildMenuOpen ? "opened" : "closed")}");
  650. }
  651. void VerifyBuildMenuReferences()
  652. {
  653. if (root == null)
  654. {
  655. Debug.LogError("Root UI element is null!");
  656. return;
  657. }
  658. if (buildMenuPanel == null)
  659. {
  660. buildMenuPanel = root.Q<VisualElement>("build-menu-panel");
  661. Debug.Log($"Re-found buildMenuPanel: {buildMenuPanel != null}");
  662. }
  663. if (buildMenuToggle == null)
  664. {
  665. buildMenuToggle = root.Q<Button>("build-menu-toggle");
  666. Debug.Log($"Re-found buildMenuToggle: {buildMenuToggle != null}");
  667. }
  668. if (buildCategoriesContainer == null)
  669. {
  670. buildCategoriesContainer = root.Q<VisualElement>("build-categories");
  671. Debug.Log($"Re-found buildCategoriesContainer: {buildCategoriesContainer != null}");
  672. }
  673. }
  674. void ShowBuildCategory(BuildingCategory category)
  675. {
  676. if (buildingSystem == null)
  677. {
  678. Debug.LogWarning("BuildingSystem not found!");
  679. return;
  680. }
  681. currentBuildCategory = category;
  682. // Show build items container
  683. if (buildItemsContainer != null)
  684. {
  685. buildItemsContainer.style.display = DisplayStyle.Flex;
  686. // Clear existing items
  687. buildItemsContainer.Clear();
  688. // Get buildings for this category
  689. var buildings = buildingSystem.GetBuildingsByCategory(category);
  690. foreach (var building in buildings)
  691. {
  692. CreateBuildingButton(building);
  693. }
  694. Debug.Log($"Showing {buildings.Count} buildings for category: {category}");
  695. }
  696. }
  697. void CreateBuildingButton(BuildingTemplate template)
  698. {
  699. Button buildButton = new Button();
  700. buildButton.text = $"{template.name}\n{buildingSystem.GetResourceCostString(template)}";
  701. buildButton.AddToClassList("build-item-button");
  702. // Check if we can afford this building
  703. bool canAfford = CanAffordBuilding(template);
  704. buildButton.SetEnabled(canAfford);
  705. buildButton.RegisterCallback<ClickEvent>(evt =>
  706. {
  707. Debug.Log($"Selected building to build: {template.name}");
  708. buildingSystem.EnterBuildMode(template);
  709. // Don't close menu immediately - let it close when build mode exits
  710. });
  711. buildItemsContainer.Add(buildButton);
  712. }
  713. bool CanAffordBuilding(BuildingTemplate template)
  714. {
  715. if (GameManager.Instance?.resourceManager == null) return false;
  716. foreach (var cost in template.costs)
  717. {
  718. if (!GameManager.Instance.resourceManager.HasResource(cost.resourceType, cost.amount))
  719. {
  720. return false;
  721. }
  722. }
  723. return true;
  724. }
  725. void UpdateBuildingButtonStates()
  726. {
  727. if (buildItemsContainer == null || buildingSystem == null) return;
  728. var buttons = buildItemsContainer.Query<Button>().ToList();
  729. var templates = buildingSystem.GetBuildingTemplates();
  730. for (int i = 0; i < buttons.Count && i < templates.Count; i++)
  731. {
  732. bool canAfford = CanAffordBuilding(templates[i]);
  733. buttons[i].SetEnabled(canAfford);
  734. }
  735. }
  736. void OnBuildModeEntered()
  737. {
  738. if (buildModeStatusLabel != null)
  739. {
  740. buildModeStatusLabel.text = "Build Mode Active - Left click to place, Right click or ESC to cancel";
  741. buildModeStatusLabel.style.display = DisplayStyle.Flex;
  742. }
  743. }
  744. void OnBuildModeExited()
  745. {
  746. if (buildModeStatusLabel != null)
  747. {
  748. buildModeStatusLabel.text = "";
  749. buildModeStatusLabel.style.display = DisplayStyle.None;
  750. }
  751. // Keep build menu open if it was open
  752. if (isBuildMenuOpen)
  753. {
  754. if (buildCategoriesContainer != null)
  755. {
  756. buildCategoriesContainer.style.display = DisplayStyle.Flex;
  757. Debug.Log("Build menu categories visibility preserved as Flex");
  758. }
  759. if (buildMenuToggle != null)
  760. {
  761. buildMenuToggle.text = "Close Build Menu";
  762. }
  763. }
  764. // Ensure build menu panel is always visible (contains toggle button)
  765. if (buildMenuPanel != null)
  766. {
  767. buildMenuPanel.style.display = DisplayStyle.Flex;
  768. }
  769. Debug.Log($"Build mode exited - UI status cleared, build menu state: {(isBuildMenuOpen ? "OPEN" : "CLOSED")}");
  770. }
  771. // Public method to force build menu visibility check
  772. public void EnsureBuildMenuAccessible()
  773. {
  774. VerifyBuildMenuReferences();
  775. if (buildMenuToggle != null)
  776. {
  777. buildMenuToggle.style.display = DisplayStyle.Flex;
  778. Debug.Log("Ensured build menu toggle is visible");
  779. }
  780. // Ensure build menu panel is always visible (contains toggle button)
  781. if (buildMenuPanel != null)
  782. {
  783. buildMenuPanel.style.display = DisplayStyle.Flex;
  784. Debug.Log("Ensured build menu panel is visible");
  785. }
  786. // If menu was supposed to be open, make sure categories are visible
  787. if (isBuildMenuOpen && buildCategoriesContainer != null)
  788. {
  789. buildCategoriesContainer.style.display = DisplayStyle.Flex;
  790. Debug.Log("Ensured build menu categories are visible");
  791. }
  792. }
  793. // Debug method to check build menu state
  794. [System.Diagnostics.Conditional("UNITY_EDITOR")]
  795. public void DebugBuildMenuState()
  796. {
  797. Debug.Log("=== BUILD MENU DEBUG INFO ===");
  798. Debug.Log($"isBuildMenuOpen: {isBuildMenuOpen}");
  799. Debug.Log($"buildMenuPanel: {(buildMenuPanel != null ? "FOUND" : "NULL")}");
  800. Debug.Log($"buildMenuToggle: {(buildMenuToggle != null ? "FOUND" : "NULL")}");
  801. Debug.Log($"buildCategoriesContainer: {(buildCategoriesContainer != null ? "FOUND" : "NULL")}");
  802. Debug.Log($"buildItemsContainer: {(buildItemsContainer != null ? "FOUND" : "NULL")}");
  803. if (buildMenuPanel != null)
  804. {
  805. Debug.Log($"buildMenuPanel display: {buildMenuPanel.style.display.value}");
  806. }
  807. if (buildMenuToggle != null)
  808. {
  809. Debug.Log($"buildMenuToggle display: {buildMenuToggle.style.display.value}");
  810. Debug.Log($"buildMenuToggle text: {buildMenuToggle.text}");
  811. }
  812. Debug.Log("=============================");
  813. }
  814. // Housing System Methods
  815. void UpdateHousingStatus(int housedVillagers, int totalVillagers)
  816. {
  817. if (housingStatusLabel != null)
  818. {
  819. housingStatusLabel.text = $"Housing: {housedVillagers}/{totalVillagers} villagers housed";
  820. }
  821. // Hide warning if housing is adequate
  822. if (housedVillagers >= totalVillagers && housingWarningLabel != null)
  823. {
  824. housingWarningLabel.style.display = DisplayStyle.None;
  825. }
  826. }
  827. void ShowHousingWarning(string warningMessage)
  828. {
  829. if (housingWarningLabel != null)
  830. {
  831. housingWarningLabel.text = warningMessage;
  832. housingWarningLabel.style.display = DisplayStyle.Flex;
  833. }
  834. }
  835. }