Unity中如何将游戏场景的分数对象传递至游戏结束场景?
实现游戏结束场景显示当前分数与最高分的方案
1. 修改现有Score脚本,添加分数持久化逻辑
原脚本仅实时更新游戏内分数,需在游戏结束时将当前分数保存到本地存储(PlayerPrefs),同时对比并更新最高分。新增OnGameEnd()方法,在游戏结束触发时调用(比如玩家死亡、时间耗尽等场景):
using UnityEngine; using UnityEngine.UI; public class Score : MonoBehaviour { public Text scoreText; public float scoreAmount; public float pointIncreasedPerSecond; void Start() { scoreAmount = 0f; pointIncreasedPerSecond = 1f; } void Update() { scoreText.text = ((int)scoreAmount).ToString(); scoreAmount += pointIncreasedPerSecond * Time.deltaTime; } // 游戏结束时调用此方法 public void OnGameEnd() { int currentScore = (int)scoreAmount; // 保存当前分数 PlayerPrefs.SetInt("CurrentScore", currentScore); // 获取本地存储的最高分,无记录则默认0 int highScore = PlayerPrefs.GetInt("HighScore", 0); // 当前分数更高时更新最高分 if (currentScore > highScore) { PlayerPrefs.SetInt("HighScore", currentScore); } // 提交保存确保数据写入本地 PlayerPrefs.Save(); } }
2. 游戏结束场景的UI与显示脚本
在游戏结束场景中添加两个Text组件(命名为CurrentScoreText和HighScoreText),创建新脚本EndGameScoreDisplay读取并显示分数:
using UnityEngine; using UnityEngine.UI; public class EndGameScoreDisplay : MonoBehaviour { public Text currentScoreText; public Text highScoreText; void Start() { // 读取本地存储的分数数据 int currentScore = PlayerPrefs.GetInt("CurrentScore", 0); int highScore = PlayerPrefs.GetInt("HighScore", 0); // 更新UI文本 currentScoreText.text = $"当前分数: {currentScore}"; highScoreText.text = $"最高分: {highScore}"; } }
3. 触发游戏结束流程
在游戏结束的触发逻辑中(比如玩家死亡检测、时间耗尽脚本),调用Score组件的OnGameEnd()方法,再切换到游戏结束场景:
using UnityEngine; using UnityEngine.SceneManagement; public class GameManager : MonoBehaviour { // 示例:玩家死亡时触发游戏结束 public void OnPlayerDeath() { Score scoreScript = FindObjectOfType<Score>(); scoreScript?.OnGameEnd(); // 替换为你的游戏结束场景名称 SceneManager.LoadScene("GameEndScene"); } }
内容的提问来源于stack exchange,提问作者GameDevEG
相关产品推荐
相关产品推荐

