Hi All,
I’ve built a custom MonoBehaviour and a custom Editor to go with it. Some of the data in the MonoBehaviour needs to be serialized but is not of any of the types supported by Unity’s internal serialization framework. My solution to this is to create an artificial serialization of the data in a supported type (in this case, a string). However, the editor doesn’t seem to like this. Once I stop a run, all the settings in my custom component (as seen in the editor) go back to their defaults.
Here’s a C# example of my implementation. Note: This is just an example. The actual code has complex fields of types not supported by the serialization framework (not bools).
public class SerializeTest : MonoBehaviour
{
///Property allowing access to the internal boolean field.
public bool testBool
{
get
{
return m_testBool;
}
set
{
// store the new value
m_testBool = value;
// update the serialized value
if(value == true)
m_serialBool = "true";
else
m_serialBool = "false";
}
}
///Read-only access to the serialized version of the boolean field.
public string serialized
{
get
{
return m_serialBool;
}
}
private void Awake()
{
// deserialize m_testBool
if(m_serialBool == "true")
m_testBool = true;
else
m_testBool = false;
}
/// boolean value
private bool m_testBool;
///Serializable version of the boolean value
[SerializeField]
private string m_serialBool;
}
and
[CustomEditor(typeof(SerializeTest))]
class SerializeTestEditor : Editor
{
/**
* Callback method, lays out the target SiblingReview component within the inspector tool in
* the Unity editor. Triggered:
* 1) Each frame, and
* 2) Whenever the user interacts with the GUI.
*/
public override void OnInspectorGUI()
{
SerializeTest stest = (SerializeTest)target;
// set up the gui to use default inspector styles
EditorGUIUtility.LookLikeInspector();
EditorGUILayout.BeginVertical();
stest.testBool = EditorGUILayout.Toggle("testBool", stest.testBool);
EditorGUILayout.TextField("testString", stest.serialized);
EditorGUILayout.EndVertical();
if(GUI.changed)
EditorUtility.SetDirty(target);
}
}
To see the problem,
- Put these scripts into the appropriate folders
- Add a SerializeTest component to an object
- In the inspector, mark “testBool” as checked (corresponds to a true value)
- Press “Play” in the editor
- Make sure the object with SerializeTest is selected in the inspector, and press “Play” again to stop the run
- The state of “testBool” will have reverted to its default ‘false’ state.
Does anybody have Ideas/Alternatives of how to make this state persistent across runs?