Unity报错CS0117:ScoreSystem无HighscoreKey定义问题求助
报错信息
测试Unity游戏脚本时触发编译错误:error CS0117: 'ScoreSystem' does not contain a definition for 'HighscoreKey'
触发报错的MainMenu脚本代码如下:
using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using TMPro; public class MainMenu : MonoBehaviour { [SerializeField] private TMP_Text HighscoreText; private void Start() { int Highscore = PlayerPrefs.GetInt(ScoreSystem.HighscoreKey, 0); HighscoreText.text = $"High Score: {Highscore}"; } public void Play() { SceneManager.LoadScene(1); } }
错误原因
代码在Start方法中尝试访问ScoreSystem类的HighscoreKey成员,但当前项目中的ScoreSystem类没有定义这个公共可访问的静态成员,编译器找不到对应定义就会抛出CS0117错误。
修复方法
二选一即可:
方案1:在
ScoreSystem类中补充对应静态常量定义(推荐,方便统一管理PlayerPrefs键名,避免拼写错误)
打开你的ScoreSystem脚本,在类内部补充如下定义即可,原有逻辑保持不变:public class ScoreSystem : MonoBehaviour { // 新增这行常量定义,名称和调用处完全匹配 public const string HighscoreKey = "GameHighScore"; // 省略ScoreSystem原有其他代码 }注意:这里定义的键名字符串要和你存储最高分时调用
PlayerPrefs.SetInt()传入的键名完全一致,否则会读取不到正确的历史最高分。方案2:如果不需要单独通过ScoreSystem管理键名,直接在读取PlayerPrefs时硬编码键名即可,把
Start方法中读取最高分的代码修改为:// 字符串内容和你存最高分用的键名保持一致 int Highscore = PlayerPrefs.GetInt("GameHighScore", 0);
内容的提问来源于stack exchange,提问作者XZAM Studios
相关产品推荐
相关产品推荐

