Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more..
    Dismiss Notice
  3. Dismiss Notice

Add Delegate function as Listener?

Discussion in 'UGUI & TextMesh Pro' started by starface606, Mar 20, 2015.

  1. starface606

    starface606

    Joined:
    Sep 5, 2014
    Posts:
    7
    Hey there guys! i would like to add a listener to a slider-component via script.
    i know i can access the onValueChanged() - callback to fill in some function, BUT:
    is it possible to add a delegate function as a listener?

    example:

    delegate void UpdateSliderValue();
    UpdateSliderValue method;

    slider.onValueChanged.AddListener(method);

    with this i get an error, so i would like to know how i can add a delegate, if possible:)

    thanks in advance!
     
  2. blizzy

    blizzy

    Joined:
    Apr 27, 2014
    Posts:
    775
    It should work if you modify your delegate to take a float parameter. (explanation)
     
  3. Feaver1968

    Feaver1968

    Joined:
    Nov 16, 2014
    Posts:
    70
    I have code like this that works:
    Code (CSharp):
    1.     Slider slider;
    2.  
    3.     void Awake()
    4.     {
    5.         slider = GetComponent<Slider>();
    6.         if (slider == null)
    7.         {
    8.             return;
    9.         }
    10.         slider.onValueChanged.AddListener(onValueChanged);
    11.     }
    12.  
    13.     void onValueChanged(float newValue)
    14.     {
    15.         Debug.Log(string.Format("Slider\t{0}\tonValueChanged:\t{1}", gameObject.name, newValue));
    16.     }
     
  4. starface606

    starface606

    Joined:
    Sep 5, 2014
    Posts:
    7
    wow, that was fast, thanks! i will try it out:) and report of course
     
  5. humanMusic

    humanMusic

    Joined:
    May 16, 2017
    Posts:
    9
    >and report of course

    Hey! You didn't report!