Search Unity

Remove callback from TextField

Discussion in 'UI Toolkit' started by HRDev, Dec 25, 2021.

  1. HRDev

    HRDev

    Joined:
    Jun 4, 2018
    Posts:
    58
    Hello to everyone.
    I register an event like this:
    Code (CSharp):
    1. textFieldExample.Q(TextField.textInputUssName).RegisterCallback<KeyUpEvent>(e => functionExample("hello"));
    Now i am trying to remove it but i can't in any way, any suggestions?
     
  2. dlorre

    dlorre

    Joined:
    Apr 12, 2020
    Posts:
    699
    You can do it like that:

    Code (CSharp):
    1.     private void OnEnable()
    2.     {
    3.         root = GetComponent<UIDocument>().rootVisualElement;
    4.         var tf = root.Q<TextField>("my-textfield");
    5.         tf.Q(TextField.textInputUssName).RegisterCallback<KeyUpEvent>(keyUpAction);
    6.  
    7.         tf.Q(TextField.textInputUssName).UnregisterCallback<KeyUpEvent>(keyUpAction);
    8.     }
    9.  
    10.     private void keyUpAction(KeyUpEvent evt)
    11.     {
    12.         Debug.Log("hello");
    13.     }
     
  3. HRDev

    HRDev

    Joined:
    Jun 4, 2018
    Posts:
    58
    okay but i need to pass some parameters to the function, how can i do that?
     
  4. dlorre

    dlorre

    Joined:
    Apr 12, 2020
    Posts:
    699
    There are several ways to do that, one is to create a class like so:

    Code (CSharp):
    1.     class actionClass
    2.     {
    3.         public string Parameter { get; set; }
    4.         public void keyUpAction(KeyUpEvent evt)
    5.         {
    6.             Debug.Log(Parameter);
    7.         }
    8.     }
    then:

    Code (CSharp):
    1.         var ac = new actionClass();
    2.         ac.Parameter = "hello";
    3.         tf.Q(TextField.textInputUssName).RegisterCallback<KeyUpEvent>(ac.keyUpAction);
    and when you need to change the parameter you simply do:

    Code (CSharp):
    1.     ac.Parameter = "world";
     
  5. dlorre

    dlorre

    Joined:
    Apr 12, 2020
    Posts:
    699
    You can also store a parameter in the visual element userData field.