So I’ve looked at the beginner tutorial for how to save and load small bits of information using player prefs, but my problem is a little unique, in that I want my player’s exact position saved when they perform a certain action in game, and it only loads when the player dies. I know that there are other questions like this that have been answered, but I couldn’t make much sense out of the answers, either because it was in javascript, or it was done in a way that requires more in depth knowledge on the subject.
So, I was wondering if you guys could help me by taking a look at these few excerpts of my scripts and tell me what I need to do to save my player’s position, and what do I need to do to load it back up.
This is the script that contains data:
using aUnityEngine;
using System.Collections;
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
public class GameControl : MonoBehaviour {
public static GameControl control;
public GameObject player;
void Awake(){
if (control == null) {
DontDestroyOnLoad (gameObject);
control = this;
} else if (control != this) {
Destroy (gameObject);
}
}
public void Save()
{
BinaryFormatter bf = new BinaryFormatter ();
FileStream file = File.Create (Application.persistentDataPath + "/playerInfo.dat");
PlayerData data = new PlayerData ();
data.player = player;
bf.Serialize (file, data);
file.Close();
}
public void Load()
{
if (File.Exists (Application.persistentDataPath + "/playerInfo.dat")) {
BinaryFormatter bf = new BinaryFormatter ();
FileStream file = File.Open (Application.persistentDataPath + "/playerInfo.dat", FileMode.Open);
PlayerData data = (PlayerData)bf.Deserialize (file);
file.Close ();
player = data.player;
}
}
}
[Serializable]
class PlayerData
{
public GameObject player;
}
This is the script that causes a save to occur:
void Update () {
//chestclick
ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray, out hit)) {
if (Input.GetButtonDown ("Fire1")) {
if (hit.transform.name == "Chest") {
GameControl.control.Save();
}
}
}
And this is the script that loads the data:
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag ("Player")) {
GameControl.control.Load();
}
}
Keep in mind that everything seems to be set up correctly, for I am getting no errors, save for when the save/load parts of the scripts activate.