I am trying to save my game and when people press new game it resets the variables but I am getting this error. Here is my code for when you press the new game button.
public class NewGame : MonoBehaviour
{
public float aiVelocityMultiplier;
public float aiVelocity;
public float aiDistance;
public void NewGameSave()
{
aiVelocityMultiplier = 0.1f;
aiVelocity = 0.1f;
aiDistance = 50f;
SaveSystem.SavePlayer(this);
}
}
Here are my code files for saving and loading.
public class Player : MonoBehaviour
{
public float aiVelocityMultiplier;
public float aiVelocity;
public float aiDistance;
public void Start()
{
aiVelocityMultiplier += Random.Range(-0.10f, 0.10f);
aiVelocity += Random.Range(-0.05f, 0.05f);
aiDistance += Random.Range(-20f, 20f);
}
void Update()
{
if(this.transform.childCount == 1)
{
SavePlayer();
print("yes");
SceneManager.LoadScene(0);
}
}
public void SavePlayer()
{
SaveSystem.SavePlayer(this.transform.GetChild(0).gameObject.GetComponent());
}
public void LoadPlayer()
{
PlayerData data = SaveSystem.LoadPlayer();
aiVelocityMultiplier = data.aiVelocityMultiplier;
aiVelocity = data.aiVelocity;
aiDistance = data.aiDistance;
}
}
public static class SaveSystem
{
public static void SavePlayer (CubeAI player)
{
BinaryFormatter formatter = new BinaryFormatter();
string path = Path.Combine(Application.persistentDataPath, "player.fun");
FileStream stream = new FileStream(path, FileMode.Create);
PlayerData data = new PlayerData(player);
formatter.Serialize(stream, data);
stream.Close();
}
public static PlayerData LoadPlayer()
{
string path = Path.Combine(Application.persistentDataPath, "player.fun");
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
{
return null;
}
}
}
[System.Serializable]
public class PlayerData
{
public float aiVelocityMultiplier;
public float aiVelocity;
public float aiDistance;
public PlayerData (CubeAI player)
{
aiVelocityMultiplier = player.aiVelocityMultiplier;
aiVelocity = player.aiVelocity;
aiDistance = player.aiDistance;
}
}
↧