Search Unity

CustomEditor and void Serialization

Discussion in 'Immediate Mode GUI (IMGUI)' started by Diab1O, Apr 26, 2016.

  1. Diab1O

    Diab1O

    Joined:
    Mar 31, 2013
    Posts:
    318
    Hello!

    There is a class, and the extension of the inspector:

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class myClass : MonoBehaviour
    5. {
    6.     public int test1 = 1;
    7.     public int test2 = 1;
    8.  
    9.  
    10.     public void testVoid()
    11.     {
    12.         test2 = 5;
    13.     }
    14. }
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using UnityEditor;
    4.  
    5. [CustomEditor(typeof(myClass))]
    6. public class myClass_Editor : Editor
    7. {
    8.     myClass obj = null;
    9.  
    10.     SerializedProperty test1Property;
    11.  
    12.  
    13.     public void OnEnable()
    14.     {
    15.         obj = (myClass)target;
    16.  
    17.         test1Property = serializedObject.FindProperty("test1");
    18.     }
    19.  
    20.     public override void OnInspectorGUI()
    21.     {
    22.         serializedObject.Update();
    23.  
    24.  
    25.         if (GUILayout.Button("Set"))
    26.         {
    27.             test1Property.intValue = 5;
    28.             obj.testVoid();
    29.         }
    30.  
    31.         serializedObject.ApplyModifiedProperties();
    32.     }
    33. }
    After pressing the button "Set":
    test1 == 5
    test2 == 1
    Why? What to do to test2 also preserved?
     
  2. CDF

    CDF

    Joined:
    Sep 14, 2013
    Posts:
    1,311
    Code (CSharp):
    1. test1Property.intValue = 5;
    2. serializedObject.ApplyModifiedProperties();
    3. obj.testVoid();
    4. serializedObject.Update();
    You need to update the serializedObject after you make changes outside of the SerializedProperty API
     
  3. Diab1O

    Diab1O

    Joined:
    Mar 31, 2013
    Posts:
    318
    Thank you