我有问题。我做了用于保存播放器的脚本,但是它只保存位置,而不保存场景。因此,如果玩家在场景A中保存并在同一场景A中重新加载游戏,就没有问题。但是,当玩家保存在场景A中,然后将游戏加载到另一个场景B中时,不会加载已保存的场景(即A),而是仅将场景A的位置应用于当前场景B。保存位置和相关场景,包括场景本身的进度?
public class Player : MonoBehaviour {
public int level;
public int collected;
public float health;
public Image healthBar;
public float currentHealth;
public bool win;
private void Start()
{
currentHealth = health;
Clue2.objectsCollected = collected;
}
private void Update()
{
collected = Clue2.objectsCollected;
level = SceneManager.GetActiveScene().buildIndex;
}
public void SavePlayer()
{
SaveSystem.SavePlayer(this);
Debug.Log("Saved: " + this);
}
public void LoadPlayer()
{
PlayerData data = SaveSystem.LoadPlayer();
level = data.level;
health = data.health;
collected = data.collected;
Clue2.objectsCollected = collected;
win = data.win;
Vector3 position;
position.x = data.position[0];
position.y = data.position[1];
position.z = data.position[2];
transform.position = position;
}
public void TakeDamage(float damage)
{
currentHealth -= damage;
healthBar.fillAmount = currentHealth / health;
}
}
[System.Serializable]
public class PlayerData
{
public int level;
public int collected;
public float health;
public float[] position;
public bool win;
public PlayerData(Player player)
{
level = player.level;
health = player.level;
collected = player.collected;
win = player.win;
//x,y,z
position = new float[3];
position[0] = player.transform.position.x;
position[1] = player.transform.position.y;
position[2] = player.transform.position.z;
}
}
public static class SaveSystem
{
public static void SavePlayer(Player player)
{
BinaryFormatter formatter = new BinaryFormatter();
string path = Application.persistentDataPath + "/playerData.dat";
FileStream stream = new FileStream(path, FileMode.Create);
PlayerData data = new PlayerData(player);
formatter.Serialize(stream, data);
stream.Close();
Debug.Log(path);
}
public static PlayerData LoadPlayer()
{
string path = Application.persistentDataPath + "/playerData.dat";
if (File.Exists(path))
{
BinaryFormatter formatter = new BinaryFormatter();
FileStream stream = new FileStream(path, FileMode.Open);
PlayerData data = formatter.Deserialize(stream) as PlayerData;
stream.Close();
return data;
}
else
{
Debug.LogError("not found " + path);
return null;
}
}
}