Unity多预制体共用脚本导致玩家加分逻辑异常求助
Unity分数更新异常问题解决
问题说明
我正在开发一款伪移动端游戏,玩法是让玩家穿过对应分数的门,原本门上要显示数学题,得分对应题目答案,现在为了调试直接显示答案数值。
目前遇到的问题:门显示的数值是对的,但玩家穿过门时,AddScore函数加的总是最新生成的门的数值,不是当前穿过的那扇门的数值,门每3秒生成一次。
相关代码
玩家控制代码
//玩家相关代码 public static int score; void Start() { score = 0; } public void AddScore(int scoretoadd) { score += scoretoadd; Debug.Log(score); }
门预制体脚本
//每个门预制体上的脚本 public class GateScript : MonoBehaviour { public TextMeshProUGUI txt; private int qIndex; public static int points; //存储题目与对应答案的字典 Dictionary<string, int> questions = new Dictionary<string, int>() { {"4 x 3", 12}, {"8 x 8", 64}, {"4 x 4", 16}, {"3 x 9", 27}, {"9 x 7", 63} }; //Start函数在第一帧更新前调用 void Start() { //获取随机数,用于从字典中选取随机条目 qIndex = Random.Range(0, questions.Count); KeyValuePair<string, int> pair = questions.ElementAt(qIndex); //设置当前门的分数值 points = pair.Value; //修改门的显示文本 txt.text = pair.Value.ToString(); //Debug.Log(pair.Value + " " + pair.Key); } //为玩家加分的函数 private void OnTriggerEnter(Collider collision) { if (collision.gameObject.tag == "Player") { collision.gameObject.GetComponent<PlayerController>().AddScore(points); } } }
问题原因
问题出在GateScript里的public static int points——static变量是属于整个类的,不是每个门实例独有的。每次新生成门时,Start方法都会覆盖这个static变量的值,所以不管玩家穿过哪扇门,最终传递给AddScore的都是最后生成的那扇门的分数。
解决方法
把points变量的static修饰符去掉,让每个门实例都拥有自己独立的分数变量:
修改后的GateScript代码:
public class GateScript : MonoBehaviour { public TextMeshProUGUI txt; private int qIndex; // 移除static,让每个门实例保存自己的分数 public int points; //存储题目与对应答案的字典 Dictionary<string, int> questions = new Dictionary<string, int>() { {"4 x 3", 12}, {"8 x 8", 64}, {"4 x 4", 16}, {"3 x 9", 27}, {"9 x 7", 63} }; void Start() { qIndex = Random.Range(0, questions.Count); KeyValuePair<string, int> pair = questions.ElementAt(qIndex); // 给当前门实例的points赋值 points = pair.Value; txt.text = pair.Value.ToString(); } private void OnTriggerEnter(Collider collision) { if (collision.gameObject.tag == "Player") { collision.gameObject.GetComponent<PlayerController>().AddScore(points); } } }
这样修改后,每扇门都会保存自己对应的分数,玩家穿过门时,传递的就是当前这扇门的分数,不会被新生成的门覆盖了。
内容的提问来源于stack exchange,提问作者Joshua 'J-Dawg' Oakley
相关产品推荐
相关产品推荐

