这可能是一个非常简单的解决方案和问题,但我一直为此绞尽脑汁。每次我统一测试时,如果我得到的分数都比高分低,那么高分就会改变。这是我的代码。请告诉我是否需要更多。
脚本1:
using UnityEngine;
using UnityEngine.SceneManagement;
public class CheckConeDeath : MonoBehaviour {
public PlayerMovement movement;
void OnCollisionEnter(Collision CollisionInfo){
if(CollisionInfo.collider.tag=="Cone"){
movement.enabled = false;
GetComponent<Rigidbody>().constraints = RigidbodyConstraints.None;
Invoke ("EndGame", 1.5f);
}
}
void EndGame(){
PlayerPrefs.SetFloat ("finalScore", Mathf.RoundToInt(FindObjectOfType<DistanceScore>().plrz));
PlayerPrefs.Save ();
Debug.Log (PlayerPrefs.GetFloat("finalScore"));
SceneManager.LoadScene (SceneManager.GetActiveScene ().buildIndex + 1);
}
}
脚本2:
using UnityEngine;
using UnityEngine.UI;
public class finalscore : MonoBehaviour {
public Text text;
public Text highscore;
void Start(){
Debug.Log (Mathf.Round (PlayerPrefs.GetFloat ("finalScore")));
Debug.Log (PlayerPrefs.GetInt ("hs", 0));
Debug.Log (Mathf.Round (PlayerPrefs.GetFloat ("finalScore")) > PlayerPrefs.GetInt ("hs", 0));
// PlayerPrefs.SetFloat ("hs", Mathf.Round(PlayerPrefs.GetFloat("finalScore")));
highscore.text = "All time High Score: "+Mathf.Round (PlayerPrefs.GetFloat ("finalScore")).ToString ();
text.text = "Final Score: " + Mathf.Round(PlayerPrefs.GetFloat("finalScore"));
if(Mathf.Round(PlayerPrefs.GetFloat("finalScore"))<PlayerPrefs.GetInt("hs",0)){
PlayerPrefs.SetFloat ("hs", Mathf.Round (PlayerPrefs.GetFloat ("finalScore")));
highscore.text = "All time High Score: "+Mathf.Round (PlayerPrefs.GetFloat ("finalScore")).ToString ();
}
}
}
以下是发生的情况的屏幕截图:
我的高分竟然有可能下降!! 非常感谢您抽出宝贵的时间!
答案 0 :(得分:3)
我认为您在这里输入了错误的逻辑,假设finalScore
是该级别的得分,而hs
则是历史最高分
您在脚本2
中写了这一行(Mathf.Round(PlayerPrefs.GetFloat("finalScore"))<PlayerPrefs.GetInt("hs",0)
将其更改为此
(Mathf.Round(PlayerPrefs.GetFloat("finalScore"))>PlayerPrefs.GetInt("hs",0)
请注意,大于符号
答案 1 :(得分:2)
在这里,您要检查最终分数是否小于高分,然后将其设置为高分。
if(Mathf.Round(PlayerPrefs.GetFloat("finalScore"))<PlayerPrefs.GetFloat("hs",0))
只需逆转条件,它将起作用
if(Mathf.Round(PlayerPrefs.GetFloat("finalScore")) > PlayerPrefs.GetFloat("hs",0))
答案 2 :(得分:1)
尝试将finalScore
的PlayerPref更改为int
,而不是float
。有时当进行这种数学运算时,Unity很有趣。理想情况下,当需要比较或计算它们时,尝试保持相同的类型。
无论如何,您已经将其转换为int
,在这里:
PlayerPrefs.SetFloat("finalScore", Mathf.RoundToInt(FindObjectOfType<DistanceScore>().plrz));
答案 3 :(得分:1)
您的问题在这里:
redir del
您使用的是从PlayerPrefs中提取的“ finalScore”值,而不是“ hs”值。
此外,正如AstroBoy在下面的评论中指出的那样,您的if语句是向后的:
highscore.text = "All time High Score: "+Mathf.Round (PlayerPrefs.GetFloat ("finalScore")).ToString ();
仅当最终分数小于或等于高分数时,才修改“ hs”。
我也不知道您为什么不使用SetInt()
作为显然被视为整数的值。