Unity游戏打包后关卡间问答题库未更新问题求助
问题分析与解决方案:Unity打包后关卡切换时题库未更新
咱们直接说核心问题:你代码里的unanswered是静态变量,这在打包后的游戏里会导致跨场景保留状态,正是它让你卡在第一关最后一题的。
在Unity编辑器里,每次停止运行都会清空静态变量,所以你测试的时候没发现问题;但打包成独立游戏后,静态变量会在整个游戏进程中一直存在——第一关通关时unanswered只剩最后一道题,切换到新关卡后,新场景的MiniGameManager会直接复用这个旧的列表,自然只会重复显示那道题。
具体修复步骤
- 移除
unanswered的static修饰符:把它改成实例变量,让每个场景的MiniGameManager都拥有自己独立的题库列表。 - 简化
Start()方法的初始化逻辑:既然每个实例都有自己的unanswered,每次场景加载时直接从当前配置的questions数组生成新列表就行,不用再判断是否为空。 - (可选优化)抽离重复的答题逻辑:你四个按钮的点击方法几乎一模一样,把它们合并成一个公共方法能大幅减少代码冗余。
修改后的完整代码
using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; using System.Collections.Generic; public class MiniGameManager : MonoBehaviour { public Question[] questions; // 移除static修饰符,改成实例变量 private List<Question> unanswered; private Question currentQuestion; [SerializeField] private Image sprite; [SerializeField] private float timeQuestion = 1f; // 这里contCorrect如果是跨关卡统计的话可以保留static,否则也建议改成实例变量 public static int contCorrect; public Button firstSelected; void Start() { // 每次场景加载都重新初始化unanswered unanswered = questions.ToList<Question>(); contCorrect = 0; SetCurrentQuestion(); firstSelected.Select(); } void SetCurrentQuestion() { int index = UnityEngine.Random.Range(0, unanswered.Count); currentQuestion = unanswered[index]; sprite.sprite = currentQuestion.questionSprite; } IEnumerator ToQuestion() { unanswered.Remove(currentQuestion); yield return new WaitForSeconds(timeQuestion); SetCurrentQuestion(); } // 抽离公共的答题判断方法 private void CheckAnswer(int selectedAnswer) { currentQuestion.correct = (currentQuestion.answer == selectedAnswer); if (currentQuestion.correct) { contCorrect++; } if (unanswered.Count > 1) { StartCoroutine(ToQuestion()); } else { SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1, LoadSceneMode.Single); } } // 四个按钮的点击方法直接调用公共方法 public void UserSelectFirst() { CheckAnswer(0); } public void UserSelectSecond() { CheckAnswer(1); } public void UserSelectThird() { CheckAnswer(2); } public void UserSelectFourth() { CheckAnswer(3); } }
修复后逻辑说明
修改后,每个关卡的MiniGameManager实例在场景加载时,都会重新从当前场景配置的questions数组生成自己的unanswered列表,完全独立于其他关卡的实例。这样切换关卡后,新关卡的题库会正常初始化,不会再复用之前关卡的剩余题目。
另外补充一点:如果contCorrect是用来统计单关卡的正确数,建议也移除static修饰符,避免跨关卡累计;如果是全局总正确数,那保留static没问题。
内容的提问来源于stack exchange,提问作者Argo2007
相关产品推荐
相关产品推荐

