Xml Serialization - Does not save anything.
Hey guys, Can anyone help me? I have been trying to use Xml serialization method to Save/Load the unlockable Characters in the game.
The code is working and it does not give any errors. The code does save and load successfully. But it does not really save the desired values.
I think I know where I am going wrong, but I really can't figure out what the solution can be.
Here is what's inside the xml file that is saved :
<?xml version="1.0" encoding="utf-8"?>
<Character xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<price>0</price>
<opened>false</opened>
</Character>
In Details:
Basically what the script does is that when the user buys a new character, there is a bool called "opened", the script basically sets the bool value to be true. Now I need that bool value to be saved.
I am really sorry for the long code dump.
their is another script which basically callbacks this script. I have not attached that.
Here is the code:
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using System.Collections.Generic;
using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
[Serializable]
public class Character
{
[XmlIgnore]
public GameObject obj;
public string name;
public string description;
public float price;
public bool opened ; **//this sets the locked characters to unlocked.**
}
**//Main Serialization Part.**
public class SaveLoadManager
{
public static void SavePlayer(Character cars)
{
FileStream stream = new FileStream(Application.persistentDataPath + "/SaveUnlocked.xml", FileMode.OpenOrCreate);
Character data = new Character();
XmlSerializer serializer = new XmlSerializer(typeof(Character));
TextWriter textWriter = new StreamWriter(stream);
serializer.Serialize(textWriter, data);
textWriter.Close();
Debug.Log("Saved Successfully!");
}
public static Character LoadPlayer()
{
if (File.Exists(Application.persistentDataPath + "/SaveUnlocked.xml"))
{
FileStream stream = new FileStream(Application.persistentDataPath + "/SaveUnlocked.xml", FileMode.Open);
XmlSerializer serializer = new XmlSerializer(typeof(Character));
TextReader textReader = new StreamReader(stream);
Character data = (Character)serializer.Deserialize(textReader);
textReader.Close();
Debug.Log("File Load Successfull!");
return data;
}
else
{
Debug.Log("FILE not FOUND!");
return null;
}
}
}
public class CharacterSelection : MonoBehaviour {
public static Character cars;
[Header("Characters carousel")]
public Character[] characters;
public int startIndex = 0;
public float zAxis = 10;
[Tooltip("Distance between characters")]
public float xOffset = 1;
public Vector3 startObjectScale = Vector3.one;
public Vector3 zoomObjectScale = Vector3.one * 2;
public float zoomSpeed = 10;
private Character selectedCharacter;
private Material[] materials;
[Header("UI Settings")]
public GameObject rootUI;
public Button buyUIButton;
public Text charNameUIText;
public Material closeMaterial;
private Text priceText;
public Canvas CharacterCanvas;
public string pricePrefix = "";
public string pricePostfix = "$";
public string openedText = "Select";
private int current = 0;
private Vector3 mouseOriginX = Vector3.zero;
private Vector3 mouseOffsetX;
private GameObject root;
private Vector3 v = Vector3.zero;
private bool isScaling = false;
private bool isSelectorOn = false;
public Camera mainCamera;
private CSCallback callback; **//This is the reference to the callback script.**
public void Save()
{
SaveLoadManager.SavePlayer(cars);
}
public void Load()
{
SaveLoadManager.LoadPlayer();
}
void Awake ()
{
Init();
}
void Start()
{
Load();
}
void Init()
{
callback = GetComponent<CSCallback>();
if(GameObject.Find("CharacterSelectorRoot") == null)
{
root = new GameObject();
root.name = "CharacterSelectorRoot";
root.transform.parent = Camera.main.transform;
}
materials = new Material[characters.Length];
int index = 0;
foreach (Character _char in characters)
{
_char.obj.SetActive(true);
_char.obj.transform.parent = root.transform;
_char.obj.transform.localPosition = new Vector3(index * xOffset, 0, 0);
_char.obj.transform.localScale = startObjectScale;
materials[index] = _char.obj.GetComponent<Renderer>().material;
if(_char.opened == false)
{
_char.obj.GetComponent<Renderer>().material = closeMaterial;
}
index++;
}
root.SetActive(false);
priceText = buyUIButton.GetComponentInChildren<Text>();
if (callback)
{
callback.OnInit();
}
}
public bool OnSwipePanel()
{
Vector3 mousePos = Input.mousePosition;
mousePos.z = 1;
Vector3 mouseWorldPos = Camera.main.ScreenToWorldPoint(mousePos);
var pointer = new PointerEventData(EventSystem.current);
pointer.position = Camera.main.WorldToScreenPoint(mouseWorldPos);
var raycastResults = new List<RaycastResult>();
EventSystem.current.RaycastAll(pointer, raycastResults);
if (raycastResults.Count > 0)
{
return raycastResults[0].gameObject.CompareTag("SwipePanel");
}
return false;
}
public void GoToCharacter(int index)
{
root.transform.localPosition = new Vector3(index * xOffset, 0, zAxis);
ChangeCurrentIndex(index, true);
isScaling = true;
}
void Update ()
{
SwipeLoop();
}
void SwipeLoop()
{
if (Input.GetMouseButtonDown(0) && OnSwipePanel())
{
Vector3 mousePos = Input.mousePosition;
mousePos.z = 1;
mouseOriginX = Camera.main.ScreenToWorldPoint(mousePos);
v.x = root.transform.localPosition.x;
}
else
{
root.transform.localPosition = Vector3.Lerp(root.transform.localPosition,
new Vector3(current * xOffset * -1, 0, zAxis), zoomSpeed * Time.deltaTime);
}
if (Input.GetMouseButton(0) && mouseOriginX != Vector3.zero)
{
Vector3 mousePos = Input.mousePosition;
mousePos.z = 1;
mouseOffsetX = new Vector3(mouseOriginX.x - Camera.main.ScreenToWorldPoint(mousePos).x, 0, zAxis);
float clamp = Mathf.Clamp(v.x - mouseOffsetX.x, -characters.Length * xOffset + xOffset, 0);
Vector3 vec = new Vector3(clamp, 0, zAxis);
root.transform.localPosition = vec;
int index = 0;
isScaling = true;
int current = Mathf.Abs(Mathf.RoundToInt(root.transform.position.x / xOffset));
float off = root.transform.position.x / xOffset;
ChangeCurrentIndex(current);
}
if (Input.GetMouseButtonUp(0))
{
v.x = root.transform.localPosition.x;
mouseOriginX = Vector3.zero;
}
}
public void ShowSelector()
{
v.x = current * xOffset * -1;
if (callback)
{
callback.OnShowSelector();
}
isSelectorOn = true;
root.SetActive(true);
rootUI.SetActive(true);
selectedCharacter = characters[startIndex];
GoToCharacter(startIndex);
mainCamera.enabled = false;
CharacterCanvas.renderMode = RenderMode.ScreenSpaceCamera;
}
public void CloseSelector()
{
if (callback)
{
callback.OnCloseSelector();
}
isSelectorOn = false;
root.SetActive(false);
rootUI.SetActive(false);
mainCamera.enabled = true;
CharacterCanvas.renderMode = RenderMode.ScreenSpaceOverlay;
}
void ChangeCurrentIndex(int index, bool isForce = false)
{
if(index != current || isForce)
{
current = index;
if (characters[index] == selectedCharacter)
{
buyUIButton.interactable = false;
}
else
{
buyUIButton.interactable = true;
}
if (characters[index].opened)
{
characters[index].obj.GetComponent<Renderer>().material = materials[index];
priceText.text = openedText;
}
else
{
characters[index].obj.GetComponent<Renderer>().material = closeMaterial;
priceText.text = pricePrefix + characters[index].price + pricePostfix;
}
charNameUIText.text = characters[index].name;
if (callback)
{
callback.OnSwipe(index, characters[index]);
}
}
}
public void ClickToSelectCharacter()
{
if (callback)
{
callback.OnClickToSelectCharacter(current, characters[current]);
}
else
{
Debug.LogWarning("Need CSCallback script to open character");
}
}
public void OpenCharacter(int index)
{
characters[index].opened = true;
characters[index].obj.GetComponent<Renderer>().material = materials[index];
priceText.text = openedText;
Save();
}
public void SelectCharacter(int index)
{
selectedCharacter = characters[index];
startIndex = index;
buyUIButton.interactable = false;
}
public Character GetSelectedCharacter()
{
return selectedCharacter;
}
}
Answer by UnityCoach · Apr 23, 2017 at 01:14 AM
All you need to know about xml serialisation is here. Hope this helps.