c# - 使用 Playerprefs 加载玩家保存的位置和场景
问题描述
我有一个游戏,当他单击加载按钮时,我正在尝试加载玩家的位置和保存的场景。我完成了加载保存场景的部分,但是我不知道如何加载玩家保存的位置。
public class Save : MonoBehaviour
{
public Menu_Script MS;
private Vector3 CordsStored;
public Transform PlayerLocation;
private float X;
private float Z;
private float Y;
public int SceneIndex;
private void Start() {}
public void SaveScene()
{
MS.ClickSound.Play();
SceneIndex = SceneManager.GetActiveScene().buildIndex;
X = PlayerLocation.position.x;
Z = PlayerLocation.position.z;
Y = PlayerLocation.position.y;
PlayerPrefs.SetInt("Player_Z_Cord",Convert.ToInt32(Z));
PlayerPrefs.SetInt("Player_X_Cord", Convert.ToInt32(X));
PlayerPrefs.SetInt("Player_Y_Cord", Convert.ToInt32(Y));
CordsStored.z = PlayerPrefs.GetInt("Player_Z_Cord");
CordsStored.x = PlayerPrefs.GetInt("Player_X_Cord");
CordsStored.y = PlayerPrefs.GetInt("Player_Y_Cord");
PlayerPrefs.SetInt("SavedScene", SceneIndex);
PlayerPrefs.Save();
Debug.Log(SceneIndex + " " + X + " " + Z + " " + Y);
}
public async void LoadExactSceneAndPos()
{
MS.ClickSound.Play();//click sound
await Task.Delay(100);
SceneManager.LoadScene(PlayerPrefs.GetInt("SavedScene"));
PlayerLocation.position = CordsStored;
}
我试过的这个脚本不起作用,它只加载保存的场景,而不是保存的位置。对此有什么想法吗?
解决方案
SceneManager.LoadScene(PlayerPrefs.GetInt("SavedScene"));
PlayerLocation.position = CordsStored;
每次加载场景时,它都会创建一组新的游戏对象和相关组件。
现在的问题是代码仍在前一个场景中的旧Save
对象中执行,并为前一个场景中的旧对象分配值PlayerLocation
。
解决此问题的一种方法是在开始时加载玩家的位置,如下所示:
public class Player : MonoBehaviour {
// ...
private void Start(){
// Do a check to see if we just loaded from save
if (justLoadedFromSave) {
Vector3 savePos = Vector3.zero;
// Fetch save position.
savePos.z = PlayerPrefs.GetInt("Player_Z_Cord");
savePos.x = PlayerPrefs.GetInt("Player_X_Cord");
savePos.y = PlayerPrefs.GetInt("Player_Y_Cord");
// Set save position
transform.position = savePos;
}
}
// ...
}