从另一个场景中的玩家偏好访问变量

Accessing a variable from player prefs in another scene

我正在使用播放器偏好

在我的场景"Standard Game"中管理我的高分

我需要在我的另一个脚本 "SaveTest" 中访问我的变量 HighScore,它位于另一个名为 "Main Menu" 的场景中,因此我可以在达到高分时销毁标记为 DestroyUI 的对象。

我用谷歌搜索了一下,但我不确定我做错了什么。

保存测试

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SaveTest : MonoBehaviour
{
public ButtonReposition buttonrepositionscript;

void Start()
{
    DontDestroyOnLoad(gameObject);
    GameObject obj = GameObject.Find("ButtonReposition");
}

// Update is called once per frame
void Update()
{
    if (GetComponent<ButtonReposition.highscore <= 100)

    Destroy(GameObject.FindWithTag("DestroyUI"));
}
}

高分脚本

public class ButtonReposition : MonoBehaviour
{
public Button prefab;
public GameObject loseObject;
public int count;
public int highscore;
public Text countText;
public Text Highscoretext;
public Image lineimagestandard;

// Use this for initialization

void Start()
{
    PlayerPrefs.GetInt("scorePref");
    highscore = PlayerPrefs.GetInt("scorePref");
    SetHighscoretext();
    SetCountText();
    float x = Random.Range(325f, -600f);
    float y = Random.Range(250f, -450f);
    Debug.Log(x + "," + y);
    prefab.GetComponent<RectTransform>().anchoredPosition = new Vector2(x, y);
}

void Update()
{
    if (Highscoretext.name == "highscoretext")
    {
        Highscoretext.text = "highscore" + highscore;
    }

    PlayerPrefs.SetInt("scorePref", highscore);
}

将此放在您的保存测试脚本中 highscore = PlayerPrefs.GetInt("scorePref"); 就是这样。