Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

How to modify serializedObject's property with Button's action?

Discussion in 'UI Toolkit' started by 5argon, May 6, 2019.

  1. 5argon

    5argon

    Joined:
    Jun 10, 2013
    Posts:
    1,555
    In this example problem I want to make a drawer with a simple button that resets the integer property to 0, I thought this should work but it doesn't. I can't find any examples in the UIElements example project that do this either. Anything else to make this work? serializedObject.UpdateIfRequiredOrScript(); doesn't help either.

    Screenshot 2019-05-06 14.05.54.png

    Screenshot 2019-05-06 14.00.30.png

    Code (CSharp):
    1. using UnityEditor;
    2. using UnityEditor.UIElements;
    3. using UnityEngine.UIElements;
    4.  
    5. [CustomEditor(typeof(ResetInt))]
    6. public class ResetIntEditor : Editor
    7. {
    8.     public override VisualElement CreateInspectorGUI()
    9.     {
    10.         var vis = new VisualElement();
    11.         var prop = serializedObject.FindProperty("integer");
    12.         vis.Add(new PropertyField(prop));
    13.         vis.Add(new Button(() =>
    14.             {
    15.                 prop.intValue = 0;
    16.             })
    17.             { text = "Reset" }
    18.         );
    19.         return vis;
    20.     }
    21. }
     
  2. uMathieu

    uMathieu

    Unity Technologies

    Joined:
    Jun 6, 2017
    Posts:
    396
    5argon likes this.
  3. 5argon

    5argon

    Joined:
    Jun 10, 2013
    Posts:
    1,555