TitleScreenManager.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. using UnityEngine;
  2. using UnityEngine.UIElements;
  3. using UnityEngine.SceneManagement;
  4. using System.IO;
  5. public class TitleScreenManager : MonoBehaviour
  6. {
  7. private UIDocument uiDocument;
  8. private Button newGameButton;
  9. private Button loadGameButton;
  10. private Button quitButton;
  11. private void Awake()
  12. {
  13. uiDocument = GetComponent<UIDocument>();
  14. if (uiDocument == null)
  15. {
  16. Debug.LogError("UIDocument component not found on TitleScreenManager GameObject.");
  17. return;
  18. }
  19. SetupUI();
  20. }
  21. private void Start()
  22. {
  23. // Refresh the load game button state on start
  24. // This ensures it reflects the current save data status
  25. UpdateLoadGameButton();
  26. }
  27. private void SetupUI()
  28. {
  29. var root = uiDocument.rootVisualElement;
  30. // Get button references
  31. newGameButton = root.Q<Button>("NewGameButton");
  32. loadGameButton = root.Q<Button>("LoadGameButton");
  33. quitButton = root.Q<Button>("QuitButton");
  34. // Setup button events
  35. if (newGameButton != null)
  36. {
  37. newGameButton.clicked += OnNewGameClicked;
  38. }
  39. else
  40. {
  41. Debug.LogWarning("NewGameButton not found in UI Document");
  42. }
  43. if (loadGameButton != null)
  44. {
  45. loadGameButton.clicked += OnLoadGameClicked;
  46. // Check if there's a saved game and disable button if not
  47. UpdateLoadGameButton();
  48. }
  49. else
  50. {
  51. Debug.LogWarning("LoadGameButton not found in UI Document");
  52. }
  53. if (quitButton != null)
  54. {
  55. quitButton.clicked += OnQuitClicked;
  56. }
  57. else
  58. {
  59. Debug.LogWarning("QuitButton not found in UI Document");
  60. }
  61. }
  62. private void OnNewGameClicked()
  63. {
  64. Debug.Log("=== NEW GAME BUTTON CLICKED ===");
  65. // Check if there's an existing save game
  66. if (HasSavedGame())
  67. {
  68. // Show warning dialog about overwriting save data
  69. ShowNewGameWarning();
  70. return;
  71. }
  72. StartNewGame();
  73. }
  74. private void ShowNewGameWarning()
  75. {
  76. Debug.Log("Warning: Existing save game detected!");
  77. // For now, we'll use Unity's dialog system. In a full game, you'd create a proper UI dialog
  78. #if UNITY_EDITOR
  79. bool confirmed = UnityEditor.EditorUtility.DisplayDialog(
  80. "New Game Warning",
  81. "You have an existing saved game. Starting a new game will overwrite your current progress.\n\nDo you want to continue?",
  82. "Start New Game",
  83. "Cancel"
  84. );
  85. if (confirmed)
  86. {
  87. StartNewGame();
  88. }
  89. #else
  90. // In builds, we'll assume user confirms for now
  91. // In a real game, implement a proper UI dialog system
  92. Debug.LogWarning("Existing save detected - proceeding with new game (implement proper dialog for builds)");
  93. StartNewGame();
  94. #endif
  95. }
  96. private void StartNewGame()
  97. {
  98. Debug.Log("Starting new game...");
  99. // Clear any existing save data FIRST, before setting new game flag
  100. Debug.Log($"🔍 Before ClearSaveData(): IsNewGame = {PlayerPrefs.GetInt("IsNewGame", -1)}");
  101. ClearSaveData();
  102. PlayerPrefs.SetInt("IsNewGame", 1); // Set new game flag
  103. PlayerPrefs.Save();
  104. Debug.Log($"🔍 After ClearSaveData(): IsNewGame = {PlayerPrefs.GetInt("IsNewGame", -1)}");
  105. // Initialize GameStateManager for new game (this sets the IsNewGame flag)
  106. if (GameStateManager.Instance != null)
  107. {
  108. GameStateManager.Instance.StartNewGame();
  109. Debug.Log($"🔍 After GameStateManager.StartNewGame(): IsNewGame = {PlayerPrefs.GetInt("IsNewGame", -1)}");
  110. }
  111. // Try to load the main team select scene
  112. string targetScene = "MainTeamSelectScene";
  113. if (SceneExists(targetScene))
  114. {
  115. SceneManager.LoadScene(targetScene);
  116. }
  117. else
  118. {
  119. Debug.LogError($"Scene '{targetScene}' not found in Build Settings! Please add it to Build Settings.");
  120. // Let's also log all available scenes for debugging
  121. LogAllScenesInBuild();
  122. }
  123. }
  124. private void OnLoadGameClicked()
  125. {
  126. Debug.Log("=== LOAD GAME BUTTON CLICKED ===");
  127. Debug.Log("Loading saved game...");
  128. // Debug current PlayerPrefs state before making any decisions
  129. DebugCurrentPlayerPrefsState();
  130. // Double-check if we have a saved game (this should always be true due to button state)
  131. if (HasSavedGame())
  132. {
  133. // Initialize/Load the GameStateManager
  134. if (GameStateManager.Instance != null)
  135. {
  136. GameStateManager.Instance.LoadGame();
  137. Debug.Log($"GameStateManager loaded: teamSetupComplete={GameStateManager.Instance.teamSetupComplete}, hasGeneratedMap={GameStateManager.Instance.hasGeneratedMap}");
  138. }
  139. else
  140. {
  141. Debug.Log("GameStateManager.Instance is null - relying on PlayerPrefs only");
  142. }
  143. // Determine where to go based on game progress
  144. // If we have completed characters AND they have proceeded past team setup, go to MapScene2
  145. // Otherwise, go to team selection to allow modifications
  146. bool shouldGoToMap = ShouldLoadDirectlyToMap();
  147. if (shouldGoToMap)
  148. {
  149. // Team is ready and has progressed past setup, go to MapScene2
  150. string targetScene = "MapScene2";
  151. Debug.Log($"Team is complete and game has progressed! Loading {targetScene}...");
  152. if (SceneExists(targetScene))
  153. {
  154. SceneManager.LoadScene(targetScene);
  155. }
  156. else
  157. {
  158. Debug.LogError($"Scene '{targetScene}' not found! Falling back to MainTeamSelectScene");
  159. SceneManager.LoadScene("MainTeamSelectScene");
  160. }
  161. }
  162. else
  163. {
  164. // Team setup not complete or hasn't progressed, go to team selection
  165. string targetScene = "MainTeamSelectScene";
  166. Debug.Log($"Team setup incomplete or hasn't progressed past setup. Loading {targetScene}...");
  167. if (SceneExists(targetScene))
  168. {
  169. SceneManager.LoadScene(targetScene);
  170. }
  171. else
  172. {
  173. Debug.LogError($"Scene '{targetScene}' not found in Build Settings!");
  174. LogAllScenesInBuild();
  175. }
  176. }
  177. }
  178. else
  179. {
  180. Debug.LogWarning("Load Game clicked but no saved game found!");
  181. // Update button state to reflect current save status
  182. UpdateLoadGameButton();
  183. }
  184. }
  185. private void DebugCurrentPlayerPrefsState()
  186. {
  187. Debug.Log("=== CURRENT PLAYERPREFS STATE ===");
  188. // Check team completion flags
  189. bool teamSetupComplete = PlayerPrefs.HasKey("TeamSetupComplete") && PlayerPrefs.GetInt("TeamSetupComplete") == 1;
  190. bool hasGeneratedMap = PlayerPrefs.HasKey("HasGeneratedMap") && PlayerPrefs.GetInt("HasGeneratedMap") == 1;
  191. Debug.Log($"TeamSetupComplete: {teamSetupComplete} (raw: {PlayerPrefs.GetInt("TeamSetupComplete", -1)})");
  192. Debug.Log($"HasGeneratedMap: {hasGeneratedMap} (raw: {PlayerPrefs.GetInt("HasGeneratedMap", -1)})");
  193. // Check characters
  194. int characterCount = 0;
  195. for (int i = 0; i < 4; i++)
  196. {
  197. string existsKey = $"Character{i}_Exists";
  198. bool exists = PlayerPrefs.HasKey(existsKey) && PlayerPrefs.GetInt(existsKey) == 1;
  199. if (exists)
  200. {
  201. characterCount++;
  202. string name = PlayerPrefs.GetString($"Character{i}_Name", "UNKNOWN");
  203. Debug.Log($"Character {i}: {name} (exists)");
  204. }
  205. }
  206. Debug.Log($"Total characters: {characterCount}");
  207. Debug.Log("=== END PLAYERPREFS STATE ===");
  208. }
  209. private bool ShouldLoadDirectlyToMap()
  210. {
  211. // Check if the game has progressed beyond initial team setup
  212. // This means: team is complete AND they have clicked "Proceed to Battle" at least once
  213. // First check if we have any characters
  214. if (!HasSavedGame()) return false;
  215. // Check if GameStateManager indicates team setup is complete
  216. bool teamComplete = false;
  217. if (GameStateManager.Instance != null)
  218. {
  219. teamComplete = GameStateManager.Instance.teamSetupComplete;
  220. Debug.Log($"GameStateManager found: teamSetupComplete = {teamComplete}");
  221. }
  222. else
  223. {
  224. Debug.Log("No GameStateManager found, checking PlayerPrefs for team completion");
  225. }
  226. // If GameStateManager doesn't indicate completion, check PlayerPrefs directly
  227. if (!teamComplete)
  228. {
  229. // Count characters
  230. int characterCount = 0;
  231. for (int i = 0; i < 4; i++)
  232. {
  233. if (PlayerPrefs.HasKey($"Character{i}_Exists") && PlayerPrefs.GetInt($"Character{i}_Exists") == 1)
  234. {
  235. characterCount++;
  236. }
  237. }
  238. // Check if team setup was marked complete in PlayerPrefs
  239. bool teamSetupCompleteInPrefs = PlayerPrefs.HasKey("TeamSetupComplete") && PlayerPrefs.GetInt("TeamSetupComplete") == 1;
  240. // Check if the game has been started (indicated by map generation)
  241. bool hasGeneratedMap = PlayerPrefs.HasKey("HasGeneratedMap") && PlayerPrefs.GetInt("HasGeneratedMap") == 1;
  242. // Team is complete if we have characters AND (team setup complete OR map generated)
  243. teamComplete = characterCount > 0 && (teamSetupCompleteInPrefs || hasGeneratedMap);
  244. Debug.Log($"PlayerPrefs check: characters={characterCount}, teamSetupComplete={teamSetupCompleteInPrefs}, hasGeneratedMap={hasGeneratedMap}");
  245. }
  246. Debug.Log($"ShouldLoadDirectlyToMap: final result = {teamComplete}");
  247. return teamComplete;
  248. }
  249. private void OnQuitClicked()
  250. {
  251. Debug.Log("Quitting game...");
  252. #if UNITY_EDITOR
  253. UnityEditor.EditorApplication.isPlaying = false;
  254. #else
  255. Application.Quit();
  256. #endif
  257. }
  258. private void UpdateLoadGameButton()
  259. {
  260. if (loadGameButton != null)
  261. {
  262. bool hasSavedGame = HasSavedGame();
  263. Debug.Log($"UpdateLoadGameButton: HasSavedGame = {hasSavedGame}");
  264. // Disable the button if no saved game
  265. loadGameButton.SetEnabled(hasSavedGame);
  266. if (!hasSavedGame)
  267. {
  268. loadGameButton.AddToClassList("disabled-button");
  269. loadGameButton.tooltip = "No saved game available";
  270. // Make the button visually appear disabled
  271. loadGameButton.style.opacity = 0.5f;
  272. // Remove click event temporarily by replacing it
  273. loadGameButton.clicked -= OnLoadGameClicked;
  274. }
  275. else
  276. {
  277. loadGameButton.RemoveFromClassList("disabled-button");
  278. loadGameButton.tooltip = "Load your saved game";
  279. loadGameButton.style.opacity = 1.0f;
  280. // Re-add click event if not already added
  281. loadGameButton.clicked -= OnLoadGameClicked; // Remove first to prevent duplicates
  282. loadGameButton.clicked += OnLoadGameClicked;
  283. }
  284. }
  285. }
  286. private bool HasSavedGame()
  287. {
  288. // Check if we have any characters saved
  289. // Look for at least one character that exists
  290. for (int i = 0; i < 4; i++)
  291. {
  292. if (PlayerPrefs.HasKey($"Character{i}_Exists") && PlayerPrefs.GetInt($"Character{i}_Exists") == 1)
  293. {
  294. return true;
  295. }
  296. }
  297. return false;
  298. }
  299. private bool SceneExists(string sceneName)
  300. {
  301. // Check if scene is in build settings
  302. for (int i = 0; i < SceneManager.sceneCountInBuildSettings; i++)
  303. {
  304. string scenePath = SceneUtility.GetScenePathByBuildIndex(i);
  305. string sceneNameFromPath = System.IO.Path.GetFileNameWithoutExtension(scenePath);
  306. if (sceneNameFromPath.Equals(sceneName, System.StringComparison.OrdinalIgnoreCase))
  307. {
  308. return true;
  309. }
  310. }
  311. return false;
  312. }
  313. private void ClearSaveData()
  314. {
  315. Debug.Log("🧹 TitleScreenManager.ClearSaveData() - clearing save data but preserving IsNewGame flag");
  316. // Clear character data
  317. for (int i = 0; i < 4; i++)
  318. {
  319. string prefix = $"Character{i}_";
  320. PlayerPrefs.DeleteKey(prefix + "Exists");
  321. PlayerPrefs.DeleteKey(prefix + "Name");
  322. PlayerPrefs.DeleteKey(prefix + "IsMale");
  323. PlayerPrefs.DeleteKey(prefix + "Strength");
  324. PlayerPrefs.DeleteKey(prefix + "Dexterity");
  325. PlayerPrefs.DeleteKey(prefix + "Constitution");
  326. PlayerPrefs.DeleteKey(prefix + "Wisdom");
  327. PlayerPrefs.DeleteKey(prefix + "Perception");
  328. PlayerPrefs.DeleteKey(prefix + "Gold");
  329. PlayerPrefs.DeleteKey(prefix + "Silver");
  330. PlayerPrefs.DeleteKey(prefix + "Copper");
  331. }
  332. // Clear team finalization flags - THIS WAS MISSING!
  333. PlayerPrefs.DeleteKey("TeamSetupComplete");
  334. PlayerPrefs.DeleteKey("HasGeneratedMap");
  335. // Clear map data
  336. PlayerPrefs.DeleteKey("MapSeed");
  337. PlayerPrefs.DeleteKey("MapWidth");
  338. PlayerPrefs.DeleteKey("MapHeight");
  339. PlayerPrefs.DeleteKey("MapNoiseScale");
  340. PlayerPrefs.DeleteKey("MapOceanThreshold");
  341. PlayerPrefs.DeleteKey("MapMountainThreshold");
  342. PlayerPrefs.DeleteKey("MapForestThreshold");
  343. // NOTE: We explicitly DO NOT clear "IsNewGame" here - it needs to persist
  344. PlayerPrefs.Save();
  345. Debug.Log("Save data cleared for new game - including team finalization flags");
  346. }
  347. private void OnEnable()
  348. {
  349. // Update load button state when the screen becomes active
  350. UpdateLoadGameButton();
  351. }
  352. private void LogAllScenesInBuild()
  353. {
  354. Debug.Log("=== ALL SCENES IN BUILD SETTINGS ===");
  355. for (int i = 0; i < SceneManager.sceneCountInBuildSettings; i++)
  356. {
  357. string scenePath = SceneUtility.GetScenePathByBuildIndex(i);
  358. string sceneName = Path.GetFileNameWithoutExtension(scenePath);
  359. Debug.Log($"Index {i}: {sceneName} ({scenePath})");
  360. }
  361. Debug.Log("=== END SCENE LIST ===");
  362. }
  363. // Call this from inspector for debugging
  364. [ContextMenu("Check Build Settings")]
  365. public void CheckBuildSettings()
  366. {
  367. LogAllScenesInBuild();
  368. bool mainTeamSelectExists = SceneExists("MainTeamSelectScene");
  369. Debug.Log($"MainTeamSelectScene in Build Settings: {mainTeamSelectExists}");
  370. bool hasSave = HasSavedGame();
  371. Debug.Log($"Has saved game: {hasSave}");
  372. }
  373. }