GameUI.cs 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053
  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. // Check if Builder job requires a Builder's Workshop
  321. if (job == JobType.Builder)
  322. {
  323. GameObject[] workshops = GameObject.FindGameObjectsWithTag("BuildingWorkshop");
  324. if (workshops == null || workshops.Length == 0)
  325. {
  326. Debug.LogWarning("⚠️ Cannot assign Builder job - No Builder's Workshop found! Build one first.");
  327. ShowTemporaryMessage("Need Builder's Workshop to train builders!");
  328. return;
  329. }
  330. }
  331. Debug.Log($"Assigning job {job} to stored villager: {currentSelectedVillager.name}");
  332. // Find the closest available workplace for this job
  333. GameObject workplace = GameManager.Instance.villagerManager.FindWorkplaceForJob(job, currentSelectedVillager.transform.position);
  334. if (workplace != null)
  335. {
  336. // Assign villager to specific workplace
  337. GameManager.Instance.villagerManager.AssignVillagerToSpecificWorkplace(currentSelectedVillager, job, workplace);
  338. Debug.Log($"Assigned {currentSelectedVillager.name} to {job} at {workplace.name}");
  339. }
  340. else
  341. {
  342. // Fallback to general job assignment if no specific workplace found
  343. GameManager.Instance.villagerManager.AssignVillagerToJob(currentSelectedVillager, job);
  344. Debug.Log($"Assigned {currentSelectedVillager.name} to {job} (no specific workplace found)");
  345. }
  346. // Deselect the villager to prevent accidental clicks
  347. if (GameManager.Instance?.selectionManager != null)
  348. {
  349. GameManager.Instance.selectionManager.DeselectAll();
  350. }
  351. }
  352. void ShowTemporaryMessage(string message)
  353. {
  354. if (buildModeStatusLabel != null)
  355. {
  356. buildModeStatusLabel.text = message;
  357. buildModeStatusLabel.style.display = DisplayStyle.Flex;
  358. buildModeStatusLabel.style.color = Color.yellow;
  359. }
  360. // Clear after 3 seconds
  361. StartCoroutine(ClearMessageAfterDelay(3f));
  362. }
  363. System.Collections.IEnumerator ClearMessageAfterDelay(float delay)
  364. {
  365. yield return new WaitForSeconds(delay);
  366. if (buildModeStatusLabel != null)
  367. {
  368. buildModeStatusLabel.style.display = DisplayStyle.None;
  369. }
  370. }
  371. void SubscribeToEvents()
  372. {
  373. // Subscribe to resource changes
  374. ResourceManager.OnResourceChanged += UpdateResourceDisplay;
  375. // Subscribe to time changes
  376. TimeManager.OnTimeSpeedChanged += UpdateTimeDisplay;
  377. TimeManager.OnPauseStateChanged += UpdatePauseDisplay;
  378. // Subscribe to villager selection
  379. Villager.OnVillagerSelected += UpdateVillagerPanel;
  380. // Subscribe to building system events
  381. BuildingSystem.OnBuildModeEntered += OnBuildModeEntered;
  382. BuildingSystem.OnBuildModeExited += OnBuildModeExited;
  383. // Subscribe to housing events
  384. HousingManager.OnHousingStatusChanged += UpdateHousingStatus;
  385. HousingManager.OnHousingWarning += ShowHousingWarning;
  386. // Subscribe to selection changes
  387. SelectionManager.OnSelectionChanged += OnSelectionChanged;
  388. // Get references to building system components
  389. buildingSystem = FindFirstObjectByType<BuildingSystem>();
  390. housingManager = FindFirstObjectByType<HousingManager>();
  391. if (buildingSystem == null)
  392. {
  393. Debug.LogWarning("BuildingSystem not found! Build menu will not work properly.");
  394. }
  395. if (housingManager == null)
  396. {
  397. Debug.LogWarning("HousingManager not found! Housing warnings will not work.");
  398. }
  399. }
  400. void OnDestroy()
  401. {
  402. // Unsubscribe from events
  403. ResourceManager.OnResourceChanged -= UpdateResourceDisplay;
  404. TimeManager.OnTimeSpeedChanged -= UpdateTimeDisplay;
  405. TimeManager.OnPauseStateChanged -= UpdatePauseDisplay;
  406. Villager.OnVillagerSelected -= UpdateVillagerPanel;
  407. // Unsubscribe from building system events
  408. BuildingSystem.OnBuildModeEntered -= OnBuildModeEntered;
  409. BuildingSystem.OnBuildModeExited -= OnBuildModeExited;
  410. // Unsubscribe from housing events
  411. HousingManager.OnHousingStatusChanged -= UpdateHousingStatus;
  412. HousingManager.OnHousingWarning -= ShowHousingWarning;
  413. }
  414. void UpdateAllUI()
  415. {
  416. // Update resource displays
  417. if (GameManager.Instance?.resourceManager != null)
  418. {
  419. var resources = GameManager.Instance.resourceManager.GetAllResources();
  420. foreach (var kvp in resources)
  421. {
  422. UpdateResourceDisplay(kvp.Key, kvp.Value);
  423. }
  424. }
  425. // Update time display
  426. if (GameManager.Instance?.timeManager != null)
  427. {
  428. UpdateTimeDisplay(GameManager.Instance.timeManager.CurrentTimeScale);
  429. UpdatePauseDisplay(GameManager.Instance.timeManager.IsPaused);
  430. }
  431. // Update selection
  432. UpdateSelectionPanel();
  433. }
  434. void UpdateResourceDisplay(ResourceType type, int amount)
  435. {
  436. Label targetLabel = null;
  437. string elementName = "";
  438. switch (type)
  439. {
  440. case ResourceType.Wood:
  441. targetLabel = woodLabel;
  442. elementName = "wood-amount";
  443. break;
  444. case ResourceType.Stone:
  445. targetLabel = stoneLabel;
  446. elementName = "stone-amount";
  447. break;
  448. case ResourceType.Food:
  449. targetLabel = foodLabel;
  450. elementName = "food-amount";
  451. break;
  452. }
  453. if (targetLabel != null)
  454. {
  455. targetLabel.text = amount.ToString();
  456. Debug.Log($"Updated {type} to {amount} successfully");
  457. // Update building button states when resources change
  458. UpdateBuildingButtonStates();
  459. }
  460. else
  461. {
  462. Debug.LogWarning($"Could not find UI label for {type} (looking for '{elementName}')");
  463. // Try to re-find the element
  464. if (root != null)
  465. {
  466. targetLabel = root.Q<Label>(elementName);
  467. if (targetLabel != null)
  468. {
  469. targetLabel.text = amount.ToString();
  470. Debug.Log($"Re-found and updated {type} to {amount}");
  471. // Update the cached reference
  472. switch (type)
  473. {
  474. case ResourceType.Wood: woodLabel = targetLabel; break;
  475. case ResourceType.Stone: stoneLabel = targetLabel; break;
  476. case ResourceType.Food: foodLabel = targetLabel; break;
  477. }
  478. }
  479. else
  480. {
  481. Debug.LogError($"Element '{elementName}' not found in UXML! Check that the UXML file contains an element with name='{elementName}'");
  482. }
  483. }
  484. }
  485. }
  486. void UpdateTimeDisplay(float timeScale)
  487. {
  488. if (timeSpeedLabel != null)
  489. {
  490. if (timeScale == 0f)
  491. {
  492. timeSpeedLabel.text = "Paused";
  493. }
  494. else if (timeScale == 1f)
  495. {
  496. timeSpeedLabel.text = "1x";
  497. }
  498. else if (timeScale == 2f)
  499. {
  500. timeSpeedLabel.text = "2x";
  501. }
  502. else if (timeScale == 10f)
  503. {
  504. timeSpeedLabel.text = "10x";
  505. }
  506. else
  507. {
  508. timeSpeedLabel.text = $"{timeScale}x";
  509. }
  510. Debug.Log($"Updated time speed to {timeSpeedLabel.text}");
  511. }
  512. else
  513. {
  514. Debug.LogWarning("Time speed label not found!");
  515. }
  516. }
  517. void UpdatePauseDisplay(bool isPaused)
  518. {
  519. if (pauseButton != null)
  520. {
  521. pauseButton.text = isPaused ? "Resume" : "Pause";
  522. Debug.Log($"Updated pause button to: {pauseButton.text}");
  523. }
  524. if (timeSpeedLabel != null && isPaused)
  525. {
  526. timeSpeedLabel.text = "Paused";
  527. }
  528. }
  529. public void UpdateVillagerPanel(Villager villager)
  530. {
  531. Debug.Log($"UpdateVillagerPanel called for: {(villager != null ? villager.name : "null")}");
  532. // Store the villager reference for job assignment
  533. currentSelectedVillager = villager;
  534. Debug.Log($"Stored villager reference: {(currentSelectedVillager != null ? currentSelectedVillager.name : "null")}");
  535. if (villagerInfoLabel == null)
  536. {
  537. Debug.LogWarning("villagerInfoLabel is null - cannot show villager info");
  538. return;
  539. }
  540. // Update job button states
  541. UpdateJobButtonStates(villager);
  542. if (villager == null)
  543. {
  544. villagerInfoLabel.text = "No villager selected";
  545. Debug.Log("Updated villager panel: No villager selected");
  546. }
  547. else
  548. {
  549. string jobText = villager.currentJob == JobType.None ? "Unemployed" : GetJobDisplayName(villager.currentJob);
  550. string info = $"Name: {villager.name}\n" +
  551. $"Job: {jobText}\n" +
  552. $"Experience: {villager.experience.GetExperienceForJob(villager.currentJob):F1}\n" +
  553. $"State: {villager.state}";
  554. villagerInfoLabel.text = info;
  555. Debug.Log($"Updated villager panel with info: {info}");
  556. }
  557. }
  558. void UpdateJobButtonStates(Villager selectedVillager)
  559. {
  560. bool hasSelection = selectedVillager != null;
  561. bool hasBuilderWorkshop = GameObject.FindGameObjectsWithTag("BuildingWorkshop").Length > 0;
  562. // Enable/disable all job buttons based on villager selection
  563. foreach (var button in jobButtons)
  564. {
  565. string buttonJobName = button.text;
  566. bool shouldEnable = hasSelection;
  567. // Special check for Builder button - requires workshop
  568. if (buttonJobName == "Builder")
  569. {
  570. shouldEnable = hasSelection && hasBuilderWorkshop;
  571. if (hasSelection && !hasBuilderWorkshop)
  572. {
  573. button.tooltip = "Requires Builder's Workshop";
  574. }
  575. else
  576. {
  577. button.tooltip = "";
  578. }
  579. }
  580. button.SetEnabled(shouldEnable);
  581. // Optional: Change button appearance based on villager's current job
  582. if (hasSelection)
  583. {
  584. string currentJobName = GetJobDisplayName(selectedVillager.currentJob);
  585. if (buttonJobName == currentJobName)
  586. {
  587. button.AddToClassList("current-job"); // You can style this in USS
  588. }
  589. else
  590. {
  591. button.RemoveFromClassList("current-job");
  592. }
  593. }
  594. }
  595. Debug.Log($"Job buttons {(hasSelection ? "enabled" : "disabled")} - {jobButtons.Count} buttons updated");
  596. }
  597. // Public method to manually refresh all UI elements
  598. public void ManualUIRefresh()
  599. {
  600. Debug.Log("Manual UI refresh requested");
  601. // Re-find all UI elements
  602. if (root != null)
  603. {
  604. woodLabel = root.Q<Label>("wood-amount");
  605. stoneLabel = root.Q<Label>("stone-amount");
  606. foodLabel = root.Q<Label>("food-amount");
  607. villagerInfoLabel = root.Q<Label>("villager-info");
  608. selectionInfoLabel = root.Q<Label>("selection-info");
  609. Debug.Log($"Re-found UI elements - Wood: {woodLabel != null}, Stone: {stoneLabel != null}, Food: {foodLabel != null}, VillagerInfo: {villagerInfoLabel != null}");
  610. // Force update all displays
  611. UpdateAllUI();
  612. }
  613. }
  614. void Update()
  615. {
  616. // Check for debug key to manually refresh UI
  617. if (Keyboard.current != null && Keyboard.current.f5Key.wasPressedThisFrame)
  618. {
  619. Debug.Log("F5 pressed - Manual UI refresh");
  620. ManualUIRefresh();
  621. }
  622. }
  623. void OnSelectionChanged()
  624. {
  625. UpdateSelectionPanel();
  626. }
  627. void UpdateSelectionPanel()
  628. {
  629. if (selectionInfoLabel == null) return;
  630. var selectedObject = GameManager.Instance?.selectionManager?.SelectedObject;
  631. var selectedVillager = GameManager.Instance?.selectionManager?.SelectedVillager;
  632. if (selectedObject == null && selectedVillager == null)
  633. {
  634. selectionInfoLabel.text = "Nothing selected";
  635. return;
  636. }
  637. string info = "";
  638. if (selectedVillager != null)
  639. {
  640. info = $"Selected: {selectedVillager.name}";
  641. }
  642. else if (selectedObject != null)
  643. {
  644. // Add specific info based on object type
  645. Building building = selectedObject.GetComponent<Building>();
  646. if (building != null)
  647. {
  648. info = building.GetBuildingInfo();
  649. }
  650. else
  651. {
  652. ResourceNode node = selectedObject.GetComponent<ResourceNode>();
  653. if (node != null)
  654. {
  655. info = node.GetNodeInfo();
  656. }
  657. else
  658. {
  659. Field field = selectedObject.GetComponent<Field>();
  660. if (field != null)
  661. {
  662. info = field.GetFieldInfo();
  663. }
  664. else
  665. {
  666. ConstructionSite site = selectedObject.GetComponent<ConstructionSite>();
  667. if (site != null)
  668. {
  669. info = site.GetConstructionInfo();
  670. }
  671. else
  672. {
  673. info = "Selected: " + selectedObject.name;
  674. }
  675. }
  676. }
  677. }
  678. }
  679. selectionInfoLabel.text = info;
  680. }
  681. // Build Menu Methods
  682. void ToggleBuildMenu()
  683. {
  684. // Verify UI references first
  685. VerifyBuildMenuReferences();
  686. isBuildMenuOpen = !isBuildMenuOpen;
  687. Debug.Log($"ToggleBuildMenu called - Menu is now {(isBuildMenuOpen ? "OPEN" : "CLOSED")}");
  688. // Show/hide only the build menu categories, not the entire panel (to keep toggle visible)
  689. if (buildCategoriesContainer != null)
  690. {
  691. buildCategoriesContainer.style.display = isBuildMenuOpen ? DisplayStyle.Flex : DisplayStyle.None;
  692. Debug.Log($"Build menu categories visibility set to: {(isBuildMenuOpen ? "Flex" : "None")}");
  693. }
  694. else
  695. {
  696. Debug.LogWarning("buildCategoriesContainer is null!");
  697. }
  698. // Ensure the build menu panel itself is always visible (contains the toggle button)
  699. if (buildMenuPanel != null)
  700. {
  701. buildMenuPanel.style.display = DisplayStyle.Flex;
  702. }
  703. if (buildMenuToggle != null)
  704. {
  705. buildMenuToggle.text = isBuildMenuOpen ? "Close Build Menu" : "Open Build Menu";
  706. // Ensure the toggle button itself is always visible
  707. buildMenuToggle.style.display = DisplayStyle.Flex;
  708. Debug.Log($"Build menu toggle text updated to: {buildMenuToggle.text}");
  709. }
  710. else
  711. {
  712. Debug.LogWarning("buildMenuToggle is null!");
  713. }
  714. // Hide build items when closing menu
  715. if (!isBuildMenuOpen && buildItemsContainer != null)
  716. {
  717. buildItemsContainer.style.display = DisplayStyle.None;
  718. }
  719. Debug.Log($"Build menu {(isBuildMenuOpen ? "opened" : "closed")}");
  720. }
  721. void VerifyBuildMenuReferences()
  722. {
  723. if (root == null)
  724. {
  725. Debug.LogError("Root UI element is null!");
  726. return;
  727. }
  728. if (buildMenuPanel == null)
  729. {
  730. buildMenuPanel = root.Q<VisualElement>("build-menu-panel");
  731. Debug.Log($"Re-found buildMenuPanel: {buildMenuPanel != null}");
  732. }
  733. if (buildMenuToggle == null)
  734. {
  735. buildMenuToggle = root.Q<Button>("build-menu-toggle");
  736. Debug.Log($"Re-found buildMenuToggle: {buildMenuToggle != null}");
  737. }
  738. if (buildCategoriesContainer == null)
  739. {
  740. buildCategoriesContainer = root.Q<VisualElement>("build-categories");
  741. Debug.Log($"Re-found buildCategoriesContainer: {buildCategoriesContainer != null}");
  742. }
  743. }
  744. void ShowBuildCategory(BuildingCategory category)
  745. {
  746. if (buildingSystem == null)
  747. {
  748. Debug.LogWarning("BuildingSystem not found!");
  749. return;
  750. }
  751. currentBuildCategory = category;
  752. // Show build items container
  753. if (buildItemsContainer != null)
  754. {
  755. buildItemsContainer.style.display = DisplayStyle.Flex;
  756. // Clear existing items
  757. buildItemsContainer.Clear();
  758. // Get buildings for this category
  759. var buildings = buildingSystem.GetBuildingsByCategory(category);
  760. foreach (var building in buildings)
  761. {
  762. CreateBuildingButton(building);
  763. }
  764. Debug.Log($"Showing {buildings.Count} buildings for category: {category}");
  765. }
  766. }
  767. void CreateBuildingButton(BuildingTemplate template)
  768. {
  769. Button buildButton = new Button();
  770. buildButton.text = $"{template.name}\n{buildingSystem.GetResourceCostString(template)}";
  771. buildButton.AddToClassList("build-item-button");
  772. // Check if we can afford this building
  773. bool canAfford = CanAffordBuilding(template);
  774. buildButton.SetEnabled(canAfford);
  775. buildButton.RegisterCallback<ClickEvent>(evt =>
  776. {
  777. Debug.Log($"Selected building to build: {template.name}");
  778. buildingSystem.EnterBuildMode(template);
  779. // Don't close menu immediately - let it close when build mode exits
  780. });
  781. buildItemsContainer.Add(buildButton);
  782. }
  783. bool CanAffordBuilding(BuildingTemplate template)
  784. {
  785. if (GameManager.Instance?.resourceManager == null) return false;
  786. foreach (var cost in template.costs)
  787. {
  788. if (!GameManager.Instance.resourceManager.HasResource(cost.resourceType, cost.amount))
  789. {
  790. return false;
  791. }
  792. }
  793. return true;
  794. }
  795. void UpdateBuildingButtonStates()
  796. {
  797. if (buildItemsContainer == null || buildingSystem == null) return;
  798. var buttons = buildItemsContainer.Query<Button>().ToList();
  799. var templates = buildingSystem.GetBuildingTemplates();
  800. for (int i = 0; i < buttons.Count && i < templates.Count; i++)
  801. {
  802. bool canAfford = CanAffordBuilding(templates[i]);
  803. buttons[i].SetEnabled(canAfford);
  804. }
  805. }
  806. void OnBuildModeEntered()
  807. {
  808. if (buildModeStatusLabel != null)
  809. {
  810. buildModeStatusLabel.text = "Build Mode Active - Left click to place, Right click or ESC to cancel";
  811. buildModeStatusLabel.style.display = DisplayStyle.Flex;
  812. }
  813. }
  814. void OnBuildModeExited()
  815. {
  816. if (buildModeStatusLabel != null)
  817. {
  818. buildModeStatusLabel.text = "";
  819. buildModeStatusLabel.style.display = DisplayStyle.None;
  820. }
  821. // Keep build menu open if it was open
  822. if (isBuildMenuOpen)
  823. {
  824. if (buildCategoriesContainer != null)
  825. {
  826. buildCategoriesContainer.style.display = DisplayStyle.Flex;
  827. Debug.Log("Build menu categories visibility preserved as Flex");
  828. }
  829. if (buildMenuToggle != null)
  830. {
  831. buildMenuToggle.text = "Close Build Menu";
  832. }
  833. }
  834. // Ensure build menu panel is always visible (contains toggle button)
  835. if (buildMenuPanel != null)
  836. {
  837. buildMenuPanel.style.display = DisplayStyle.Flex;
  838. }
  839. Debug.Log($"Build mode exited - UI status cleared, build menu state: {(isBuildMenuOpen ? "OPEN" : "CLOSED")}");
  840. }
  841. // Public method to force build menu visibility check
  842. public void EnsureBuildMenuAccessible()
  843. {
  844. VerifyBuildMenuReferences();
  845. if (buildMenuToggle != null)
  846. {
  847. buildMenuToggle.style.display = DisplayStyle.Flex;
  848. Debug.Log("Ensured build menu toggle is visible");
  849. }
  850. // Ensure build menu panel is always visible (contains toggle button)
  851. if (buildMenuPanel != null)
  852. {
  853. buildMenuPanel.style.display = DisplayStyle.Flex;
  854. Debug.Log("Ensured build menu panel is visible");
  855. }
  856. // If menu was supposed to be open, make sure categories are visible
  857. if (isBuildMenuOpen && buildCategoriesContainer != null)
  858. {
  859. buildCategoriesContainer.style.display = DisplayStyle.Flex;
  860. Debug.Log("Ensured build menu categories are visible");
  861. }
  862. }
  863. // Debug method to check build menu state
  864. [System.Diagnostics.Conditional("UNITY_EDITOR")]
  865. public void DebugBuildMenuState()
  866. {
  867. Debug.Log("=== BUILD MENU DEBUG INFO ===");
  868. Debug.Log($"isBuildMenuOpen: {isBuildMenuOpen}");
  869. Debug.Log($"buildMenuPanel: {(buildMenuPanel != null ? "FOUND" : "NULL")}");
  870. Debug.Log($"buildMenuToggle: {(buildMenuToggle != null ? "FOUND" : "NULL")}");
  871. Debug.Log($"buildCategoriesContainer: {(buildCategoriesContainer != null ? "FOUND" : "NULL")}");
  872. Debug.Log($"buildItemsContainer: {(buildItemsContainer != null ? "FOUND" : "NULL")}");
  873. if (buildMenuPanel != null)
  874. {
  875. Debug.Log($"buildMenuPanel display: {buildMenuPanel.style.display.value}");
  876. }
  877. if (buildMenuToggle != null)
  878. {
  879. Debug.Log($"buildMenuToggle display: {buildMenuToggle.style.display.value}");
  880. Debug.Log($"buildMenuToggle text: {buildMenuToggle.text}");
  881. }
  882. Debug.Log("=============================");
  883. }
  884. // Housing System Methods
  885. void UpdateHousingStatus(int housedVillagers, int totalVillagers)
  886. {
  887. if (housingStatusLabel != null)
  888. {
  889. housingStatusLabel.text = $"Housing: {housedVillagers}/{totalVillagers} villagers housed";
  890. }
  891. // Hide warning if housing is adequate
  892. if (housedVillagers >= totalVillagers && housingWarningLabel != null)
  893. {
  894. housingWarningLabel.style.display = DisplayStyle.None;
  895. }
  896. }
  897. void ShowHousingWarning(string warningMessage)
  898. {
  899. if (housingWarningLabel != null)
  900. {
  901. housingWarningLabel.text = warningMessage;
  902. housingWarningLabel.style.display = DisplayStyle.Flex;
  903. }
  904. }
  905. }