Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
  • Help Room /
avatar image
1
Question by Rony · Apr 22, 2017 at 07:54 PM · c#saveloadxmlserializersave-to-file

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;
        
     }  
 }








Comment
Add comment
10 |3000 characters needed characters left characters exceeded
â–¼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by UnityCoach · Apr 23, 2017 at 01:14 AM

All you need to know about xml serialisation is here. Hope this helps.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
â–¼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

338 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

How to save player score? (C#) 0 Answers

How to save and load a player position, health, rotation in a particular scene. 0 Answers

Saving and Loading from scene to scene.. 0 Answers

Save/Load Serialization by @Cherno 0 Answers

How can I save (and load) my multiple object? 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges