保存和显示高分,跨类统一变量



我需要从我的其他类获取变量分数,并将其设置为userprefs键。我的GUI标签Ingame似乎没有设置,如果没有userprefs键"高"。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Threading;
public class Player : MonoBehaviour {
public Vector2 jumpForce = new Vector2(0, 300);
private Rigidbody2D rb2d;
Generator SwagScript;
GameObject generator;

// Use this for initialization
void Start () {
    rb2d = gameObject.GetComponent<Rigidbody2D>();
    generator = GameObject.FindGameObjectWithTag("Generator");
    SwagScript = generator.GetComponent<Generator>();
}
// Update is called once per frame
void Update () {
    if (Input.GetKeyUp("space"))
    {
        rb2d.velocity = Vector2.zero;
        rb2d.AddForce(jumpForce);
    }
    Vector2 screenPosition = Camera.main.WorldToScreenPoint(transform.position);
    if (screenPosition.y > Screen.height || screenPosition.y < 0)
    {
        Die();
    }
}
void OnCollisionEnter2D(Collision2D other)
{
    Die();
}
void Die()
{
    if (PlayerPrefs.HasKey("HighScore"))
    {
        if (PlayerPrefs.GetInt("Highscore") < SwagScript.score)
        {
            PlayerPrefs.SetInt("HighScore", SwagScript.score);
        }
        else
        {
            PlayerPrefs.SetInt("HighScore", SwagScript.score);
        }
    }
    Application.LoadLevel(Application.loadedLevel);
}

}

除非您在其他地方创建Highscore playerpref,否则Die()方法永远不会创建它,因为if (PlayerPrefs.HasKey("HighScore"))总是会返回false。

只需删除。

最新更新