Search Unity

[SOLVED] Replicating GUILayout.TextArea

Discussion in 'UI Toolkit' started by andymads, Jan 15, 2020.

  1. andymads

    andymads

    Joined:
    Jun 16, 2011
    Posts:
    1,614
    As an exercise I tried converting one of my custom inspectors to use UIElements.

    In my original code I have a TextArea that uses a string field local to the inspector class.

    Code (CSharp):
    1. string json;
    2.  
    3. public override void OnInspectorGUI()
    4. {
    5.     json = GUILayout.TextArea(json);
    6.  
    7.     if (GUILayout.Button("Do something"))
    8.     {
    9.         // do something with json string
    10.     }
    11. }
    I had to use IMGUIContainer for this bit as I just don't know how to get the TextArea working with UIElements. I tried using a TextField but when I click in it it just goes blank. Do I need to somehow bind it to the string field?
     
  2. andymads

    andymads

    Joined:
    Jun 16, 2011
    Posts:
    1,614
    Ok, solved it.

    I simply needed to register a callback for value changed.

    Code (CSharp):
    1.            
    2.             var textField = new TextField();
    3.             textField.RegisterValueChangedCallback((e) => {
    4.                 json = textField.value = e.newValue;
    5.             });
    6.  
     
  3. uDamian

    uDamian

    Unity Technologies

    Joined:
    Dec 11, 2017
    Posts:
    1,231
    Just a note that you don't need to re-set the
    textField.value
    in your
    RegisterValueChangedCallback()
    .
    textField.value = something
    is actually what triggers a ChangeEvent and the only reason this is not an infinite loop is that we do an equality check before we send the event.
     
    andymads likes this.