- Home /
How do I serialize a class?
Hello, I am trying to make a class of variables that are hidden (serialized). This is similar to the playermotor script that comes with unity. You have the little arrow to extend the field.
Also, there is no active/ non active check box next to the script however i don't know if this a problem or not.
How do I achieve this? So far I have this code but nothing shows up:
using UnityEngine;
using System.Collections;
public class Script : MonoBehaviour {
[System.Serializable]
public class example
{
public float myFloat = 1;
}
}
The checkbox only appears if the script will behave differently depending on the value of enabled
. Start
, Update
, and FixedUpdate
are some methods which make the tick appear. If you don't have those methods you don't need the tick.
Answer by steakpinball · Feb 26, 2015 at 06:34 PM
Make a field of your serializable class in your script.
[System.Serializable] // This allows fields of this type to appear in the inspector
public class Example {
// These fields will become visible when the arrow is clicked
public float myFloat = 0.1f;
}
// This is your script on the game object
public class Script : MonoBehaviour {
public Example field;
}
Thank you brianturner, now everything is working fine.
Answer by loyum · Feb 25, 2015 at 07:24 PM
Hello, Do it like that:
using UnityEngine;
using System.Collections;
using System.Xml.Serialization;
using System.IO;
public class Script : MonoBehaviour {
public class Example
{
public float myFloat = 1;
}
public void serializeExample(Example example) {
XmlSerializer serializer = new XmlSerializer(typeof(Example));
TextWriter writer = new StreamWriter("saveFile.xml");
serializer.Serialize(writer, example);
writer.Close();
}
}
I didn't test it, but it should work :)
Good luck!
loyum, when i do it the way you suggested, still nothing shows up in the inspector.
Are you actually creating an instance? Simply declaring does not do anything. You need to also add an instance reference.
What do you actually want? Concerning the tick for active/inactive, are you expecting that for your new class? Because this is only for $$anonymous$$onoBehaviour classes.
Your answer
Follow this Question
Related Questions
Transform object issues 1 Answer
Bringing Down the Buttons 0 Answers
Custom assets give Missing (Mono Script) 0 Answers
OnSerializeNetworkView is not called 1 Answer
Assets Returning Null 0 Answers