Saving Variables with XML [Solved w/ PlayerPrefs!]

I know some of you are thinking “Man, not this again!” but I’ve looked through Google, and this forum for the answer to my question and haven’t found a single solution. I have tried using the source code on the Unity Wiki and tried to implement what I want but, I’m a total noob, and can’t figure out a way to do this.

The project I’m trying to make is an agenda where the user can write down their schedule, projects, and assignments. So far, I only made the schedule, and it consists of 64 string variables.

I want to make the Save/Load on a different script so, how do I get the save script to save variables from another the schedule script and, when it is loaded, how can I load the info back to where it was written?

You could probably use the PlayerPrefs class (Unity - Scripting API: PlayerPrefs) to save/load the data.

try my save tool

http://bladestudios.x10hosting.com/u3dst.html

That tool seems like overkill for this simple task.

use JSON.NET. Decorate your properties with [JsonProperty], JsonWriter.Write(filename), JsonReader.Read(filename).

My syntax may not be exact.

I’ve seen this many times, but I don’t know how to implement it…

… And I agree.

How can I use this with Unity?

Use the SetString method (Unity - Scripting API: PlayerPrefs.SetString) to save some of your data:

PlayerPrefs.SetString(“Variable1”, myScript.Variable1);

Then use GetString (Unity - Scripting API: PlayerPrefs.GetString) to retrieve and assign it back:

myScript.Variable1 = PlayerPrefs.GetString(“Variable1”)

If your variables for your schedule has things like integers or floats, you can use GetInteger, SetFloat, etc.

That makes more sense than the documentation. The page says “Player Name” and “Foobar” and the code at the top doesn’t make much sense either.

So, I put this in the .plist?

What’s “.plist”? Just write the code in whichever of your scripts makes sense.

I tried whit this code (note my comments are in spanish):

import System;
import System.Collections;
import System.Xml;
import System.Xml.Serialization;
import System.IO;
import System.Text;
// La informacion a guardar en el XML se debe poner en la siguiente funcion
class DemoData {
	var NombreCentro : String;
	var Puntos = 0;
}

// UserData es una clase personalizada que los objetos que queremos salvar en el XML
 class UserData {
    // Tenemos que definir una estructura default de la estructura
   public var _iUser : DemoData = new DemoData();
    // Hasta el momento el constructor no ha hecho nada....
   function UserData() { }
}

// Estos son nuestras funciones básicas privadas
private var _FileLocation : String;
private var _FileName : String;
private var myData : UserData;
private var _data : String;
//Estas son variables que yo habia definido
private var usuario : String;
var usuario2 : String;
private var archivo : String;
var mensaje : String;
var nombre = "";

function Awake () { 
    // Where we want to save and load to and from
    ruta = Application.dataPath;
	if (Application.isEditor){
		usuario = "pruebas.unity3d?u=1234567890";
		_FileLocation="G:/xmls/";
	}else{
		usuario = ""+Application.srcValue;
		_FileLocation=Application.dataPath + "/xmls/";
	}
	usuario2= usuario.Substring(18, usuario.Length - 18);
	_FileName = usuario2+".xml";
      // we need soemthing to store the information into
      myData=new UserData();
   }
   
function Start (){
if (Application.isEditor){
mensaje = "Se salvara con Cien mil Puntos";
myData._iUser.Puntos = 100000;
}
}

function OnGUI(){
GUI.Label (Rect (0, 0, Screen.width, 25), "Ruta de guardado: "+_FileLocation);
GUI.Label (Rect (0, 25, Screen.width, 25), "Embeed: "+usuario);
if (Application.isEditor){
GUI.Label (Rect (0, 50, Screen.width, 25), "Archivo: No aplica en modo editor.");
}else{
GUI.Label (Rect (0, 50, Screen.width, 25), "Archivo: "+Application.srcValue);
}
GUI.Label (Rect (0, 75, Screen.width, 25), "Usuario: "+usuario2);

//INGRESADO DEL NUEVO
 if (GUI.Button(Rect(0,100,100,25),"Cargar")) {     
      GUI.Label(Rect(0,200,Screen.width-200,25),"Cargando desde: "+_FileLocation);
      // La siguiente funcion carga los datos para el usuario
      LoadXML();
      if(_data.ToString() != ""){
		/*
		Notar como se hace la referencia a UserData aqui, así es como se puede integrar
		la información de manera correcta
		//myData = (UserData)DeserializeObject(_data);
		*/
		myData = DeserializeObject(_data);
		//Carga los datos en un XML
		//Cada linea carga un dato, puede armar tambien los Vector3 a partir de tres datos
		NombreCentro = myData._iUser.NombreCentro;
		Puntos = myData._iUser.Puntos;
		}
   }
   if (GUI.Button(Rect(0,125,100,25),"Guardar")) {
   NombreCentro = nombre;
	GUI.Label(Rect (0, 225, Screen.width -225,25),"Salvar a: "+_FileLocation);
	//Las siguientes lineas armaran los datos en el XML
	myData._iUser.NombreCentro = NombreCentro;
	if (Application.isEditor){
	myData._iUser.Puntos = 100000;
	}else{
	myData._iUser.Puntos = Puntos;
	}
	//	Hora de armar el XML
	_data = SerializeObject(myData);
	CreateXML();
	mensaje = mensaje + "\n" + _data;
   }
   GUI.Label(Rect (0, 250, 100,30),"Nombre del Centro:");
   nombre = GUI.TextField (Rect (100, 250, 200, 30), nombre);
   GUI.Label(Rect (0, 280, 300,25),"Nombre del Centro: "+myData._iUser.NombreCentro);
   GUI.Label(Rect (0, 300, 300,25),"Puntos: "+myData._iUser.Puntos);
   GUI.TextField (Rect (0, 320, Screen.width, Screen.height-320), mensaje);
}

//Los siguientes metodos ayudan al UTF8 y que todo se escriba correctamente//
function UTF8ByteArrayToString(characters : byte[] ){     
   var encoding : UTF8Encoding  = new UTF8Encoding();
   var constructedString : String  = encoding.GetString(characters);
   return (constructedString);
}

function StringToUTF8ByteArray(pXmlString : String){
   var encoding : UTF8Encoding  = new UTF8Encoding();
   var byteArray : byte[]  = encoding.GetBytes(pXmlString);
   return byteArray;
}

//Aqui ya serializamos nuestro UserData a myData
function SerializeObject(pObject : Object){
   var XmlizedString : String  = null;
   var memoryStream : MemoryStream  = new MemoryStream();
   var xs : XmlSerializer = new XmlSerializer(typeof(UserData));
   var xmlTextWriter : XmlTextWriter  = new XmlTextWriter(memoryStream, Encoding.UTF8);
   xs.Serialize(xmlTextWriter, pObject);
   memoryStream = xmlTextWriter.BaseStream;
   XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
   return XmlizedString;
}

//Ahora deserializamos el objeto a su forma orginal
function DeserializeObject(pXmlizedString : String){
   var xs : XmlSerializer  = new XmlSerializer(typeof(UserData));
   var memoryStream : MemoryStream  = new MemoryStream(StringToUTF8ByteArray(pXmlizedString));
   var xmlTextWriter : XmlTextWriter  = new XmlTextWriter(memoryStream, Encoding.UTF8);
   return xs.Deserialize(memoryStream);
}

//Finalmente nuestras funciones de salvar y cargar hacen al archivo
function CreateXML(){
   var writer : StreamWriter;
   var t : FileInfo = new FileInfo(_FileLocation+"/"+ _FileName);
   if(!t.Exists){
   mensaje = mensaje + "\n" + "El archivo no existía";
      writer = t.CreateText();
   }else{
   mensaje = mensaje + "El archivo ya existe"+ "\n" ;
      t.Delete();
      writer = t.CreateText();
   }
   writer.Write(_data);
   writer.Close();
   mensaje = mensaje + "Archivo escrito."+ "\n" ;
}
   
function LoadXML(){
   var r : StreamReader = File.OpenText(_FileLocation+"/"+ _FileName);
   var _info : String = r.ReadToEnd();
   r.Close();
   _data=_info;
   mensaje = mensaje + "Archivo leido."+ "\n" ;
}

Really is a kind of DebugConsole… It works perfecly in Editor, but in webplayer detects all the data, but dosn’t save o load the XML. There’s no problem with the file permission in server… in locally makes the same issue.

Web players cannot access the user’s hard drive (essentially no file I/O) due to security restrictions.

in fact i want to save this file in a server… can be?

You can use the WWW class to transmit the data to a web page. That web page can use a server-side script (PHP, ASP.NET, etc.) to save that data to the server.

This is pretty much the code I tried to use in the beginning, but in spanish.

And, do I use the PlayerPref scripts in the .plist or what?

it can send info to a webpages,
it woks to save or load files too?

It just hits a URL and reads back any data on that page. So if you pass information to the page, it can save that. Similarly, the page can generate information dynamically and WWW can read that back.

Nobody is answering my question… >_>

uhhh…

I guess you’re using PC. The .plist is the PlayerPrefs file.

Anyways, I will try it out and see if it works.

I imagine then the file is written to and managed automatically by PlayerPrefs; as far as I know, you don’t need to (and shouldn’t be) manually handling that file.