Unity游戏开发:玩家销毁后停止计分及分数存储问题
解决方案:玩家死亡检测、停止计分与分数存储
一、修复PlayerAlive的核心bug
你的GameManager脚本中,Update()方法每帧强制将PlayerAlive设为true,这会覆盖玩家死亡时设置的false,直接导致后续逻辑失效。必须删除这个Update方法,并在Start()中初始化玩家存活状态:
修改后的GameManager初始化代码:
void Start() { score = 0; PlayerAlive = true; // 初始化玩家存活状态 UpdateScore(0); gameOverText.gameObject.SetActive(false); // 初始隐藏GameOver文本 InvokeRepeating("SpawnRandomEnemy", StartDelay, SpawnInterval); }
二、完善玩家死亡触发逻辑
在Player脚本中,正确引用GameManager,碰撞触发时执行完整死亡流程:
using UnityEngine; public class Player : MonoBehaviour { public GameManager gameManager; // 在Inspector面板拖入GameManager对象 private void OnTriggerEnter(Collider other) { if (other.CompareTag("Enemy") && gameManager.PlayerAlive) { // 标记玩家死亡 gameManager.PlayerAlive = false; // 停止生成敌人 gameManager.CancelInvoke("SpawnRandomEnemy"); // 显示GameOver文本 gameManager.gameOverText.gameObject.SetActive(true); // 销毁玩家(可根据需求调整) Destroy(gameObject); // 保存当前分数 gameManager.SaveHighScore(); } } }
三、限制计分逻辑(仅存活时加分)
修改Destroy Out of Bounds脚本,只有玩家存活时才执行加分操作:
using UnityEngine; public class DestroyOutOfBounds : MonoBehaviour { public GameManager gameManager; // 拖入GameManager对象 private void OnTriggerExit(Collider other) { if (other.CompareTag("Enemy")) { Destroy(other.gameObject); // 仅玩家存活时加分 if (gameManager.PlayerAlive) { gameManager.UpdateScore(5); } } } }
四、实现分数存储(本地保存最高分)
在GameManager中添加分数存储方法,使用PlayerPrefs实现本地持久化:
// 在GameManager类中添加以下方法 public void SaveHighScore() { // 获取当前存储的最高分,默认0 int currentHighScore = PlayerPrefs.GetInt("HighScore", 0); // 如果当前分数更高,更新并保存最高分 if (score > currentHighScore) { PlayerPrefs.SetInt("HighScore", score); PlayerPrefs.Save(); // 确保数据写入本地 } } // 可选:在Start中加载并显示最高分(需额外添加TextMeshProUGUI组件) // public TextMeshProUGUI highScoreText; // void Start() // { // // ...原有初始化代码 // int savedHighScore = PlayerPrefs.GetInt("HighScore", 0); // highScoreText.text = "High Score: " + savedHighScore; // }
内容的提问来源于stack exchange,提问作者BraveDragonWolf
相关产品推荐
相关产品推荐

