Unity游戏距离高分系统报错:无法将string隐式转换为int求解决
解决Cannot implicitly convert type 'string' to 'int'错误
错误原因
报错出在这一行:
score = MainCamera.position.x.ToString("0");
score是int类型,但ToString("0")返回的是字符串类型,直接赋值会导致类型不匹配,触发这个错误。你不需要把相机位置转成字符串再赋值给分数变量,直接处理浮点数转整数即可。
修复方案
根据你的需求选择合适的整数转换方式:
- 直接截断小数部分(取整数部分):用强制类型转换
(int) - 向下取整:
Mathf.FloorToInt() - 四舍五入取整:
Mathf.RoundToInt()
把错误行替换成以下任意一种即可,这里以强制转换为例:
score = (int)MainCamera.position.x;
修复后的完整代码
public Transform MainCamera; public Text ScoreText; public Text HighScoreText; public int score; void Start() { HighScoreText.text = PlayerPrefs.GetInt("HighScore", 0).ToString(); } void Update() { // MainCamera is follow the Player score = (int)MainCamera.position.x; // 修复后的代码 ScoreText.text = score.ToString(); if (score > PlayerPrefs.GetInt("HighScore", 0)) { PlayerPrefs.SetInt("HighScore", score); HighScoreText.text = score.ToString(); } }
额外提示
- 如果相机位置的小数部分对你的距离计算有意义,也可以把
score改成float类型,后续比较和保存时再转成int,不过当前需求用int足够。 - 每帧在
Update里更新分数是可行的,但如果相机移动频率不高,也可以考虑用事件触发更新,优化性能。
内容的提问来源于stack exchange,提问作者Timi21
相关产品推荐
相关产品推荐

