- Home /
Saving player position
i have a save + load script, and i'm trying to make something like an RPG. first major problem is that i need to save the player's position, and load it when the game is turned on again. here's the current script using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization.Formatters.Binary; using System.IO;
public static class SaveLoad {
public static void Save() {
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Create (Application.persistentDataPath + "/savedGames.gd"); //you can call it anything you want
PlayerData data = new PlayerData ();
bf.Serialize(file,data);
file.Close();
}
public static void Load() {
if(File.Exists(Application.persistentDataPath + "/savedGames.gd")) {
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/savedGames.gd", FileMode.Open);
PlayerData data=(PlayerData)bf.Deserialize (file);
file.Close();
}
}
}
[System.Serializable] class PlayerData
{
public Vector3 playerpos;
}
now, the way i understand it i'm supposed to write something like data.playerpos=transform.position;
before the bf.serialize. and when i load the game, it will be transform.position=data.playerpos;
problem is, that unity tells me i need the saveload script to be monobehaviour for the transform to be a thing, but when i change it to monobehaviour, it tells me that static classes cant derive from monobehaviour. how else can i go and try to save the playerposition?
Answer by JamesL98 · Mar 14, 2015 at 03:45 PM
have the players transform.x transform.y and transform.z saved as player prefs and then turned into a Vector3 then make the player position = the Vector3.