How do I use the Load function? - c#

For saving I created structures in the state class :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
[Serializable]
public class SaveState
{
public struct Position
{
public float x;
public float y;
public float z;
public void Fill(Vector3 v3)
{
x = v3.x;
y = v3.y;
z = v3.z;
}
public Vector3 V3 { get { return new Vector3(x, y, z); } set { Fill(value); } }
}
public struct Rotation
{
public float x;
public float y;
public float z;
public float w;
public void Fill(Quaternion Quat)
{
x = Quat.x;
y = Quat.y;
z = Quat.z;
w = Quat.w;
}
public Quaternion Qua { get { return new Quaternion(x, y, z, w); } set { Fill(value); } }
}
public struct Scale
{
public float x;
public float y;
public float z;
public float w;
public void Fill(Vector3 v3)
{
x = v3.x;
y = v3.y;
z = v3.z;
}
public Vector3 V3 { get { return new Vector3(x, y, z); } set { Fill(value); } }
}
public SaveState(Vector3 pos, Quaternion rot, Vector3 sca)
{
Position position = new Position();
position.V3 = pos;
Rotation qua = new Rotation();
qua.Qua = rot;
Scale scale = new Scale();
scale.V3 = sca;
}
}
Then in the manager script :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Runtime.Serialization.Formatters.Binary;
using System;
using System.IO;
public class SaveManager : MonoBehaviour
{
public static void Save(SaveState player)
{
BinaryFormatter formatter = new BinaryFormatter();
string path = Application.persistentDataPath + "/player.bin";
FileStream stream = new FileStream(path, FileMode.Create);
formatter.Serialize(stream, player);
stream.Close();
}
public static SaveState Load()
{
string path = Application.persistentDataPath + "/player.bin";
if (File.Exists(path))
{
BinaryFormatter formatter = new BinaryFormatter();
FileStream stream = new FileStream(path, FileMode.Open);
SaveState data = formatter.Deserialize(stream) as SaveState;
stream.Close();
return data;
}
else
{
Debug.LogError("Save file not found in " + path);
return null;
}
}
}
And test script :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SaveTest : MonoBehaviour
{
private void Update()
{
if(Input.GetKeyDown(KeyCode.T))
{
var player = GameObject.Find("Player");
SaveState saveState = new SaveState(player.transform.position, player.transform.rotation,player.transform.localScale);
SaveManager.Save(saveState);
}
if(Input.GetKeyDown(KeyCode.L))
{
var player = GameObject.Find("Player");
}
}
}
The save part seems to be ok but the load part I'm not sure.
I'm not sure if the Load function is written good and not sure how to use it in the L key input.
Edit :
My classes and scripts after updates :
Save State :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
[Serializable]
public class SaveState
{
public struct SerializableVector3
{
public float X;
public float Y;
public float Z;
public SerializableVector3(Vector3 v)
{
X = v.x;
Y = v.y;
Z = v.z;
}
// And now some magic
public static implicit operator SerializableVector3(Vector3 v)
{
return new SerializableVector3(v);
}
public static implicit operator Vector3(SerializableVector3 sv)
{
return new Vector3(sv.X, sv.Y, sv.Z);
}
}
public struct SerializableQuaternion
{
public float X;
public float Y;
public float Z;
public float W;
public SerializableQuaternion(Quaternion q)
{
X = q.x;
Y = q.y;
Z = q.z;
W = q.w;
}
public static implicit operator SerializableQuaternion(Quaternion q)
{
return new SerializableQuaternion(q);
}
public static implicit operator Quaternion(SerializableQuaternion sq)
{
return new Quaternion(sq.X, sq.Y, sq.Z, sq.W);
}
}
public SerializableVector3 position;
public SerializableQuaternion rotation;
public SerializableVector3 scale;
public SaveState(Vector3 pos, Quaternion rot, Vector3 sca)
{
position = pos;
rotation = rot;
scale = sca;
}
public void ApplyToPlayer(Transform player)
{
player.position = position;
player.rotation = rotation;
player.localScale = scale;
}
}
Manager :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Runtime.Serialization.Formatters.Binary;
using System;
using System.IO;
public class SaveManager : MonoBehaviour
{
public static void Save(SaveState player)
{
BinaryFormatter formatter = new BinaryFormatter();
string path = Application.persistentDataPath + "/player.bin";
FileStream stream = new FileStream(path, FileMode.Create);
formatter.Serialize(stream, player);
stream.Close();
}
public static SaveState Load()
{
string path = Application.persistentDataPath + "/player.bin";
if (File.Exists(path))
{
BinaryFormatter formatter = new BinaryFormatter();
FileStream stream = new FileStream(path, FileMode.Open);
SaveState data = formatter.Deserialize(stream) as SaveState;
stream.Close();
return data;
}
else
{
Debug.LogError("Save file not found in " + path);
return null;
}
}
}
Test script :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SaveTest : MonoBehaviour
{
private void Update()
{
if (Input.GetKeyDown(KeyCode.T))
{
var player = GameObject.Find("Player");
SaveState saveState = new SaveState(player.transform.position, player.transform.rotation, player.transform.localScale);
SaveManager.Save(saveState);
}
if (Input.GetKeyDown(KeyCode.L))
{
var player = GameObject.Find("Player");
var playerInfo = SaveManager.Load();
playerInfo.ApplyToPlayer(player.transform);
}
}
}

You currently don't have any fields in your class!
Only type definitions. You will need some like
public Position position;
public Rotation rotation;
public Scale scale;
The ones you used are just local method variables that won't be stored anywhere!
And in the constructor assign these
public SaveState(Vector3 pos, Quaternion rot, Vector3 sca)
{
// Since structs are never null
// you don't need to create new ones
position.V3 = pos;
rotation.Qua = rot;
scale.V3 = sca;
}
Then I usually go for a method within your class itself like e.g.
public void ApplyToPlayer(Transform player)
{
player.position = position.V3;
player.rotation = rotation.Qua;
player.localScale = scale.V3;
}
and then in your L block
var player = GameObject.Find("Player").transform;
var playerInfo = SaveManager.Load();
playerInfo.ApplyToPlayer(player);
As a last step:
For your structs I would even rather recommend to write implicit operator conversions as one example:
[Serializable]
public struct SerializableVector3
{
public float X;
public float Y;
public float Z;
public SerializableVector3(Vector3 v)
{
X = v.x;
Y = v.y;
Z = v.z;
}
// And now some magic
public static implicit operator SerializableVector3 (Vector3 v)
{
return new SerializableVector3 (v);
}
public static implicit operator Vector3 (SerializableVector3 sv)
{
return new Vector3 (sv.X, sv.Y, sv.Z);
}
}
This allows you now to simply use both types exchangeably like you could rather use
public SerializableVector3 position;
// This type is your homework
public SerializableQuaternion rotation;
public SerializableVector3 scale;
and then you can directly assign them like
player.position = someSaveStat.position;
and also
someSaveStat.position = player.position;
So you could change the constructor to e.g.
public SaveState(Vector3 pos, Quaternion rot, Vector3 sca)
{
position = pos;
rotation = rot;
scale = sca;
}
and the apply method would become
public void ApplyToPlayer (Transform player)
{
player.position = position;
player.rotation = rotation;
player.localScale = scale;
}
Note: Typed on smartphone but I hope the idea gets clear.

Load() seems to be OK.
By the way you can also use FileStream stream = File.Open(path, FileMode.Open);
Nothing really special with using it, just: SaveState save = SaveManager.Load();

Related

CrossplatformInput Joystick is not working in Unity

I have connected a joystick from the standard assets library from the unity store, but the input is not being read. The car can be controlled by the arrow keys,but the joystick is not working.
here is my code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
public class rearwheeldrive : MonoBehaviour
{
public float maxAngle = 30;
public float maxTorque = 300;
public WheelCollider[] wheelArray;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
float angle = maxAngle * CrossPlatformInputManager.GetAxis("Horizontal");
float torque = maxTorque * CrossPlatformInputManager.GetAxis("Vertical");
wheelArray[0].steerAngle = angle;
wheelArray[1].steerAngle = angle;
wheelArray[2].motorTorque = torque;
wheelArray[3].motorTorque = torque;
foreach (WheelCollider wheelcollider in wheelArray)
{
Vector3 P;
Quaternion Q;
wheelcollider.GetWorldPose(out P, out Q);
Transform wheelshape = wheelcollider.transform.GetChild(0);
wheelshape.position = P;
wheelshape.rotation = Q;
}
}
}
Even after changing maxAngle * Input.GetAxis("Horizontal"); to maxAngle * CrossPlatformInputManager.GetAxis("Horizontal"); it takes the arrow key input whilst the joystick is not working.
Code Of Joystick object
using System;
using UnityEngine;
using UnityEngine.EventSystems;
namespace UnityStandardAssets.CrossPlatformInput
{
public class Joystick : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IDragHandler
{
public enum AxisOption
{
// Options for which axes to use
Both, // Use both
OnlyHorizontal, // Only horizontal
OnlyVertical // Only vertical
}
public int MovementRange = 100;
public AxisOption axesToUse = AxisOption.Both; // The options for the axes that the still will use
public string horizontalAxisName = "Horizontal"; // The name given to the horizontal axis for the cross platform input
public string verticalAxisName = "Vertical"; // The name given to the vertical axis for the cross platform input
Vector3 m_StartPos;
bool m_UseX; // Toggle for using the x axis
bool m_UseY; // Toggle for using the Y axis
CrossPlatformInputManager.VirtualAxis m_HorizontalVirtualAxis; // Reference to the joystick in the cross platform input
CrossPlatformInputManager.VirtualAxis m_VerticalVirtualAxis; // Reference to the joystick in the cross platform input
void OnEnable()
{
CreateVirtualAxes();
}
void Start()
{
m_StartPos = transform.position;
}
void UpdateVirtualAxes(Vector3 value)
{
var delta = m_StartPos - value;
delta.y = -delta.y;
delta /= MovementRange;
if (m_UseX)
{
m_HorizontalVirtualAxis.Update(-delta.x);
}
if (m_UseY)
{
m_VerticalVirtualAxis.Update(delta.y);
}
}
void CreateVirtualAxes()
{
// set axes to use
m_UseX = (axesToUse == AxisOption.Both || axesToUse == AxisOption.OnlyHorizontal);
m_UseY = (axesToUse == AxisOption.Both || axesToUse == AxisOption.OnlyVertical);
// create new axes based on axes to use
if (m_UseX)
{
m_HorizontalVirtualAxis = new CrossPlatformInputManager.VirtualAxis(horizontalAxisName);
CrossPlatformInputManager.RegisterVirtualAxis(m_HorizontalVirtualAxis);
}
if (m_UseY)
{
m_VerticalVirtualAxis = new CrossPlatformInputManager.VirtualAxis(verticalAxisName);
CrossPlatformInputManager.RegisterVirtualAxis(m_VerticalVirtualAxis);
}
}
public void OnDrag(PointerEventData data)
{
Vector3 newPos = Vector3.zero;
if (m_UseX)
{
int delta = (int)(data.position.x - m_StartPos.x);
delta = Mathf.Clamp(delta, - MovementRange, MovementRange);
newPos.x = delta;
}
if (m_UseY)
{
int delta = (int)(data.position.y - m_StartPos.y);
delta = Mathf.Clamp(delta, -MovementRange, MovementRange);
newPos.y = delta;
}
transform.position = new Vector3(m_StartPos.x + newPos.x, m_StartPos.y + newPos.y, m_StartPos.z + newPos.z);
UpdateVirtualAxes(transform.position);
}
public void OnPointerUp(PointerEventData data)
{
transform.position = m_StartPos;
UpdateVirtualAxes(m_StartPos);
}
public void OnPointerDown(PointerEventData data) { }
void OnDisable()
{
// remove the joysticks from the cross platform input
if (m_UseX)
{
m_HorizontalVirtualAxis.Remove();
}
if (m_UseY)
{
m_VerticalVirtualAxis.Remove();
}
}
}
}
Use it Like :
public Joystick mJoystick;
float angle = maxAngle * mJoystick.Horizontal;
float torque = maxTorque * mJoystick.Vertical;
EDIT : I have used the same asset, works fine using the below settings.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
public class TestScript : MonoBehaviour
{
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
float angle = CrossPlatformInputManager.GetAxis("Horizontal");
float torque = CrossPlatformInputManager.GetAxis("Vertical");
print("Angle : " + angle + " , Torque : " + torque);
}
}

How can I add the locksystem state to my SaveState class?

The Lock System script :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LockSystem : MonoBehaviour
{
public bool mouseCursorLockState = true;
public PlayerCameraController playerCameraController;
public PlayerController playerController;
// Start is called before the first frame update
void Start()
{
MouseCursorLockState(mouseCursorLockState);
}
public void MouseCursorLockState(bool lockState)
{
if (lockState == false)
{
Cursor.visible = true;
Cursor.lockState = CursorLockMode.None;
}
else
{
Cursor.visible = false;
Cursor.lockState = CursorLockMode.Locked;
}
}
public void PlayerLockState(bool LockPlayer, bool LockPlayerCamera)
{
if (LockPlayer == true)
{
playerController.enabled = false;
}
else
{
playerController.enabled = true;
}
if (LockPlayerCamera == true)
{
playerCameraController.enabled = false;
}
else
{
playerCameraController.enabled = true;
}
}
}
I'm using it in some places in my game for example :
public LockSystem playerLockMode;
playerLockMode.PlayerLockState(true, false);
The playerLockMode is at the top and the using it in some function it's just exmaple of how I'm using it.
The Save State class. So far I can save any object position rotation scaling. Now I want to save also the locking system state :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
[Serializable]
public class SaveState
{
[Serializable]
public struct SerializableVector3
{
public float X;
public float Y;
public float Z;
public SerializableVector3(Vector3 v)
{
X = v.x;
Y = v.y;
Z = v.z;
}
// And now some magic
public static implicit operator SerializableVector3(Vector3 v)
{
return new SerializableVector3(v);
}
public static implicit operator Vector3(SerializableVector3 sv)
{
return new Vector3(sv.X, sv.Y, sv.Z);
}
}
[Serializable]
public struct SerializableQuaternion
{
public float X;
public float Y;
public float Z;
public float W;
public SerializableQuaternion(Quaternion q)
{
X = q.x;
Y = q.y;
Z = q.z;
W = q.w;
}
public static implicit operator SerializableQuaternion(Quaternion q)
{
return new SerializableQuaternion(q);
}
public static implicit operator Quaternion(SerializableQuaternion sq)
{
return new Quaternion(sq.X, sq.Y, sq.Z, sq.W);
}
}
public SerializableVector3 position;
public SerializableQuaternion rotation;
public SerializableVector3 scale;
public SaveState(Vector3 pos, Quaternion rot, Vector3 sca)
{
position = pos;
rotation = rot;
scale = sca;
}
public void ApplyToPlayer(Transform player)
{
player.localPosition = position;
player.localRotation = rotation;
player.localScale = scale;
}
public bool LockState(bool lockState)
{
return lockState;
}
}
I tried to add in the bottom the new function LockState but that's not the right way to handle it.
The save manager script :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Runtime.Serialization.Formatters.Binary;
using System;
using System.IO;
public class SaveManager : MonoBehaviour
{
public static void Save(SaveState player)
{
BinaryFormatter formatter = new BinaryFormatter();
string path = Application.persistentDataPath + "/player.bin";
FileStream stream = new FileStream(path, FileMode.Create);
formatter.Serialize(stream, player);
stream.Close();
}
public static SaveState Load()
{
string path = Application.persistentDataPath + "/player.bin";
if (File.Exists(path))
{
BinaryFormatter formatter = new BinaryFormatter();
FileStream stream = new FileStream(path, FileMode.Open);
SaveState data = formatter.Deserialize(stream) as SaveState;
stream.Close();
return data;
}
else
{
Debug.LogError("Save file not found in " + path);
return null;
}
}
}
The Player State script for saving the player state but I can also save here the lock system state just not sure yet how :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerState : MonoBehaviour
{
private void Awake()
{
Save();
}
public void Save()
{
SaveState saveState = new SaveState(transform.localPosition,
transform.localRotation, transform.localScale);
SaveManager.Save(saveState);
}
public void Load()
{
var playerInfo = SaveManager.Load();
playerInfo.ApplyToPlayer(transform);
}
}
Once the game start I'm saving in the Awake once.
Then calling the Load function to my Main Menu ui button :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class MainMenu : MonoBehaviour
{
public void StartNewGame()
{
ScenesManager.StartNewGame();
}
public void LoadGame()
{
var playerstate = GameObject.Find("Player").GetComponent<PlayerState>();
playerstate.Load();
}
public void ResumeGame()
{
ScenesManager.ResumeGame();
}
public void QuitGame()
{
Application.Quit();
}
}
My idea is to save one the game start and then using a timer and save each 5 minutes for example.
So I'm calling only the Load function in the Main Menu. The save will be automatic during the game.
In the SaveState class I want to add more and more stuff to save it's state like the locking system and also a coroutine state. The game start with a running coroutine that make some effect. I want also to save the coroutine state if the game save at the start or a bit later while the coroutine is running so save the current coroutine state too.
This is when the game start :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.PostProcessing;
public class DepthOfField : MonoBehaviour
{
public UnityEngine.GameObject player;
public PostProcessingProfile postProcessingProfile;
public bool dephOfFieldFinished = false;
public LockSystem playerLockMode;
private Animator playerAnimator;
private float clipLength;
private Coroutine depthOfFieldRoutineRef;
// Start is called before the first frame update
void Start()
{
if (depthOfFieldRoutineRef != null)
{
StopCoroutine(depthOfFieldRoutineRef);
}
playerAnimator = player.GetComponent<Animator>();
AnimationClip[] clips = playerAnimator.runtimeAnimatorController.animationClips;
foreach (AnimationClip clip in clips)
{
clipLength = clip.length;
}
DepthOfFieldInit(clipLength);
// Don't forget to set depthOfFieldRoutineRef to null again at the end of routine!
}
public void DepthOfFieldInit(float duration)
{
var depthOfField = postProcessingProfile.depthOfField.settings;
depthOfField.focalLength = 300;
StartCoroutine(changeValueOverTime(depthOfField.focalLength, 1, duration));
postProcessingProfile.depthOfField.settings = depthOfField;
}
public IEnumerator changeValueOverTime(float fromVal, float toVal, float duration)
{
playerLockMode.PlayerLockState(true, true);
float counter = 0f;
while (counter < duration)
{
var dof = postProcessingProfile.depthOfField.settings;
counter += Time.deltaTime;
float val = Mathf.Lerp(fromVal, toVal, counter / duration);
dof.focalLength = val;
postProcessingProfile.depthOfField.settings = dof;
yield return null;
}
playerAnimator.enabled = false;
dephOfFieldFinished = true;
depthOfFieldRoutineRef = null;
}
}
This is a screenshot of the game start and the effect while the coroutine is running :
This blur effect is made by the PostProcessing and the coroutine.
I want also to save the state if that.
Saving objects info is easy like position rotation and scaling but how can I save the state of other stuff like the locking system and the DepthOfField ? How should I extend the SaveState class and then how to use it to save it in the PlayerState script ?

C# Unity Text array to string to show in GameScene

I have a text array that calculates a sum: y = ax + b and now I want it to put the results of Y in a table, but I would have no idea how it should be. If I put a Debug.Log in, it sums correctly. I have no idea how to put the values of an array in a string so that it shows the values in a table in the game scene.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Line : MonoBehaviour
{
public LineRenderer lijn;
public InputField A;
public InputField B;
public float valueA;
public float valueB;
public int somX;
public double somY;
private int num = 0;
public Text[] xTabel;
public Text[] ytabel;
public Vector3 lijnposition;
void Update()
{
lijn.startWidth = 0.2F;
lijn.endWidth = 0.2F;
for(int i = -2; i < 4; i++)
{
somY = valueA *(somX * i) + valueB;
//xTabel[num] = somX.ToString();
//ytabel[num] = somY.ToString();
lijn.SetPosition(i, lijnposition);
Debug.Log(somY);
}
}
}

C# Unity Serialized Hashtable never get´s Assigned

Im working on a Game. I have a ProgressControl Class that tracks the Players Progress, and save and load that to a Binary File. Serializing Gold and Points works. Now I want to add a Hashtable to save the Points for every Level, to Limit the maximum Points a Player can get on every Level. But the Hashtable in the Serializable Class never gets assigned and stays null. So no Points are saved.
How can I get that Hashtable serialized? What am I missing?
using UnityEngine;
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Collections;
public class ProgressControl : MonoBehaviour
{
public static ProgressControl progress;
public int gold;
public int points;
public int level;
public Hashtable h;
void Awake()
{
h = new Hashtable();
if (progress == null)
{
DontDestroyOnLoad(gameObject);
progress = this;
}
else if (progress != this)
{
Destroy(gameObject);
}
}
public void save()
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Create(Application.persistentDataPath + "/playerInfo.dat");
PlayerData data = new PlayerData();
data.gold = gold;
data.points = points;
data.h = h;
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();
gold = data.gold;
points = data.points;
h = data.h;
}
}
public void saveLevel()
{
level = TargetScript.activeLevel;
Debug.Log("Level Saved");
}
public void savePointsToHashMap(int LevelKey, int points)
{
if (h.ContainsKey(LevelKey))
{
object value = h[LevelKey];
int compare = int.Parse(value.ToString());
if (compare < points)
{
h.Add(LevelKey, points);
Debug.Log("Overwrite and Save Points");
}
}
else{
Debug.Log("Save Points");
h.Add(LevelKey, points);
}
save();
}
}
[Serializable]
class PlayerData
{
public int gold;
public int points;
public Hashtable h;
}

Saving ENUMs in C# and Loading it

Im trying to save some enums in my code. Saving and converting to the string is going well. But with the loading there r some problems. I mean. I just cant load it). Im doing all that in unity. I thought to convert enum to string and after convert it back. Conversion to string works fine. But what happens with back-convestion i dont know. Thanks.
using UnityEngine;
using System.Collections;
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
public class GameControl : MonoBehaviour {
public static GameControl control;
public float health;
public float experience;
public string stateString;
public enum State { start_0, start_1, start_3, start_4 };
public State myState;
void Awake () {
if(control == null)
{
DontDestroyOnLoad(gameObject);
control = this;
}
else if(control != this)
{
Destroy(gameObject);
}
}
public void Save()
{
stateString = myState.ToString(); //Converts ENUM to STRING
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Create(Application.persistentDataPath +
"/playerInfo.dat");
PlayerData data = new PlayerData();
data.health = health;
data.experience = experience;
data.stateString = stateString;
bf.Serialize(file, data);
file.Close();
}
public void Load()
{
if(File.Exists(Application.persistentDataPath + "/playerInfo.dat"))
{
State loadedState = (State) Enum.Parse(typeof(State), stateString);
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath +
"/playerInfo.dat", FileMode.Open);
PlayerData data = (PlayerData)bf.Deserialize(file);
file.Close();
health = data.health;
experience = data.experience;
stateString = data.stateString;
}
}
}
[Serializable]
class PlayerData
{
public float health;
public float experience;
public string stateString;
public enum State { start_0, start_1, start_3, start_4 };
public State myState;
}

Categories

Resources