Search Unity

Problems with serialization of a MonoBehaviour when controlled by a CustomEditor

Discussion in 'Scripting' started by NewtonDynamics, Jun 24, 2016.

  1. NewtonDynamics

    NewtonDynamics

    Joined:
    Jun 24, 2016
    Posts:
    1
    Hi,
    I am new to Unity, for the past three weeks I am having the problem in the title.
    I first I though I was my lack of experience but as time past by the problem becomes more and more intolerable.

    Bascially for each MonoBehavior class that we control with a Custom Editor class, the class members are initialized to some strange default values each time with start the scene.
    I simplified a sample class to this.
    Code (CSharp):
    1.  
    2. [DisallowMultipleComponent]
    3. [AddComponentMenu("Newton Physics/Newton World")]
    4. public class NewtonWorld : MonoBehaviour
    5. {
    6.     public dNewtonWorld GetWorld()
    7.     {
    8.         return m_world;
    9.     }
    10.     private dNewtonWorld m_world = new dNewtonWorld();
    11.  
    12.     public int m_numberOfThreads = 0;
    13. }
    and the custom editor is this

    Code (CSharp):
    1. [CustomEditor(typeof(NewtonWorld))]
    2. public class NewtonWorldEditor: Editor
    3. {
    4.     public override void OnInspectorGUI()
    5.     {
    6.         NewtonWorld world = (NewtonWorld)target;
    7.         world.m_numberOfThreads = EditorGUILayout.IntPopup("worked threads", world.m_numberOfThreads, m_numberOfThreads, m_numberOfThreadsValues);
    8.     }
    9.  
    10.     static private int[] m_numberOfThreadsValues = { 0, 2, 3, 4, 8};
    11.     static private string[] m_numberOfThreads = { "single threaded", "2 worked threads", "3 worked threads", "4 worked threads", "8 worked threads"};
    12. }
    member variable m_numberOfThreads is set to 2 and if we have to set it each time we launch the scene.
    I have read all the documentation about serialization as well as many of the works around from various people, nothing seems to work.
    This is such a trivial and fundamental thing that I must be missing something fundamental, but I cannot determine what it is.

    Any help is appreciated.
    Julio
     
  2. FuzzyShan

    FuzzyShan

    Joined:
    Jul 30, 2012
    Posts:
    182
  3. Billy4184

    Billy4184

    Joined:
    Jul 7, 2014
    Posts:
    6,027
    I tried the code and didn't have any problems with serialization. However I had deleted the references to dNewtonWorld since I'm not sure what that is - maybe that class is changing your values at runtime?
     
  4. billykater

    billykater

    Joined:
    Mar 12, 2011
    Posts:
    329
    If you use target or targets to modify your monobehaviour from a custom inspector you have to manually tell unity that you changed some fields on it for it to be picked up by unity. See SetDirty for different ways on how to do this.