GameUI.cs 36 KB

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