[英]Unity Highscore using PlayerPrefs not working
這可能是一個非常簡單的解決方案和問題,但是我一直為此絞盡腦汁。 每次我統一測試時,如果我得到的分數都比高分低,那么高分就會改變。 這是我的代碼。 請告訴我是否需要更多。
腳本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 ();
}
}
}
這是發生的情況的屏幕截圖:
我的高分怎么可能下降! 非常感謝您的寶貴時間!
我認為您在這里輸入了錯誤的邏輯,假設finalScore
是在該級別獲得的分數,並且hs
是高分
您在腳本2中寫了這一行
(Mathf.Round(PlayerPrefs.GetFloat("finalScore"))<PlayerPrefs.GetInt("hs",0)
改成這個
(Mathf.Round(PlayerPrefs.GetFloat("finalScore"))>PlayerPrefs.GetInt("hs",0)
請注意,大於符號
在這里,您要檢查最終分數是否小於高分,然后將其設置為高分。
if(Mathf.Round(PlayerPrefs.GetFloat("finalScore"))<PlayerPrefs.GetFloat("hs",0))
只需逆轉條件,它將起作用
if(Mathf.Round(PlayerPrefs.GetFloat("finalScore")) > PlayerPrefs.GetFloat("hs",0))
嘗試將finalScore
PlayerPref更改為int
而不是float
。 有時當進行這種數學運算時,Unity很有趣。 理想情況下,當需要比較或計算它們時,嘗試保持相同的類型。
您已經將它轉換為int
了,在這里:
PlayerPrefs.SetFloat("finalScore", Mathf.RoundToInt(FindObjectOfType<DistanceScore>().plrz));
您的問題在這里:
highscore.text = "All time High Score: "+Mathf.Round (PlayerPrefs.GetFloat ("finalScore")).ToString ();
您使用的是從PlayerPrefs中提取的“ finalScore”值,而不是“ hs”值。
另外,正如AstroBoy在下面的評論中指出的那樣,您的if語句是向后的:
if(Mathf.Round(PlayerPrefs.GetFloat("finalScore")) < PlayerPrefs.GetInt("hs",0)){
您僅在最終分數小於高分時修改“ hs”。
我也不知道為什么您不使用SetInt()
作為顯然被視為整數的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.