问题描述
我是Unity的新手。我的问题是我在第一个场景中拥有一个得分,即玩家的z位置。我希望它使用PlayerPrefs将其保存到Highscore。我有2个名为MenuManager和GameManager的空对象,它们有自己的脚本,但我不知道如何共享分数的值并将其保存在PlayerPrefs中。谁能帮帮我吗?我不知道如何不在场景中分配组件。也请您帮我使用不同场景的脚本功能。我的意思是我该如何调用另一个场景中的游戏对象的功能。请帮我。我需要完成比赛。
记分脚本,用于跟踪玩家的位置。
using UnityEngine;
using UnityEngine.UI;
public class score : MonoBehavIoUr
{
public Transform player;
public Text scoreText;
public Highscore highscore;
[HideInInspector]public static float totalscore;
void Update()
{
scoreText.text = player.position.z.ToString("0");
totalscore = player.position.z;
}
}
负责我的文字更改的High score脚本,尽管我还没有从事过播放器偏好的工作,但是如果有人知道的话,请也帮我。
using UnityEngine;
using UnityEngine.UI;
public class Highscore : MonoBehavIoUr
{
static float floatscore;
public Text highscore;
private void Start()
{
highscore.text = PlayerPrefs.GetFloat("Highscore",0).ToString();
}
public void highscoreFunc()
{
PlayerPrefs.SetFloat("Highscore",floatscore);
highscore.text = floatscore.ToString();
}
public void resetscore()
{
PlayerPrefs.DeleteKey("Highscore");
}
}
using UnityEngine;
using UnityEngine.SceneManagement;
public class MenuFunctions : MonoBehavIoUr
{
public void StartGame()
{
SceneManager.LoadScene(1);
}
public void quitGame()
{
Application.Quit();
}
}
负责更改场景并重新启动游戏的游戏管理器。
using UnityEngine;
using UnityEngine.SceneManagement;
public class GameManager : MonoBehavIoUr
{
bool GameEnd = true;
public Highscore highscore;
public void EndGame()
{
if(GameEnd)
{
GameEnd = false;
Invoke("Restart",1);
}
}
void Restart()
{
SceneManager.LoadScene(sceneBuildindex: 0);
}
}
解决方法
class ScoreKeeper{
public static float HighScore;
}
//where you update player score
ScoreKeeper.HighScore= 10;//Score Value
//Where you want to fetch score
Debug.Log(ScoreKeeper.HighScore);
说明:只需创建一个类(非Mono行为)并使用静态变量来保存可在多个场景中访问的分数。
就PlayerPrefs而言,最好使用二进制文件
https://www.youtube.com/watch?v=XOjd_qU2Ido&t=825s
这是一个很好的解释。