Search Unity

  1. Unity 2018.1 has arrived! Read about it here
    Dismiss Notice
  2. Scriptable Render Pipeline improvements, Texture Mipmap Streaming, and more! Check out what we have in store for you in the 2018.2 Beta.
    Dismiss Notice
  3. If you couldn't join the live stream, take a peek at what you missed.
    Dismiss Notice
  4. Improve your Unity skills with a certified instructor in a private, interactive classroom. Learn more.
    Dismiss Notice
  5. ARCore is out of developer preview! Read about it here.
    Dismiss Notice
  6. Magic Leap’s Lumin SDK Technical Preview for Unity lets you get started creating content for Magic Leap One™. Find more information on our blog!
    Dismiss Notice
  7. Want to see the most recent patch releases? Take a peek at the patch release page.
    Dismiss Notice

Change the Value of a Toggle without triggering OnValueChanged?

Discussion in 'Unity UI & TextMesh Pro' started by webbut, Oct 20, 2014.

  1. webbut

    webbut

    Joined:
    Jun 25, 2014
    Posts:
    20
    Can You change the value of a toggle without having it call it's OnValueChanged functions?

    When the user presses the toggle i need some code to happen but sometimes i need to change the Active state of the toggle in code without triggering it's OnValueChanged. Is there a way to "silently" switch the state of a toggle?
     
    OliverPaulson and perplex_bcn like this.
  2. phil-Unity

    phil-Unity

    Unity UI Lead Developer Unity Technologies

    Joined:
    Nov 23, 2012
    Posts:
    1,060
    currently no there is not although internally we do have support for not sending it. i'll see if someone has a reason not to expose this.
     
    lermy3d likes this.
  3. webbut

    webbut

    Joined:
    Jun 25, 2014
    Posts:
    20
    It would be super helpful, I'm converting some of our old UI to the new system and I noticed that we would have some potential infinite loops if we used the OnValueChanged for a lot of things.
     
    OliverPaulson and lermy3d like this.
  4. phil-Unity

    phil-Unity

    Unity UI Lead Developer Unity Technologies

    Joined:
    Nov 23, 2012
    Posts:
    1,060
    So it seems like its not something we'll add for V1 right now. I'm sure there should be some way to avoid the infinite loop.
     
  5. webbut

    webbut

    Joined:
    Jun 25, 2014
    Posts:
    20
    Its pretty problematic whenever you are using one of the new UI elements to represent another piece of data that can change from something that isn't direct user input.

    For example if I have int X and I make a slider so the user can change the value of int x. I would make the slider's OnValueChanged change the value of X. Then if for some reason the value X changes because of some other code I have to update the value of the slider so it accurately reflects the new value of X. Setting the value of the slider in code to the new value of X would trigger the sliders OnValueChanged which would set the value of X again.

    If your OnValueChanged is doing more than just setting the value of something it can get pretty annoying.
     
    XGT08, sergiobd and rakkarage like this.
  6. Karth

    Karth

    Joined:
    Mar 10, 2014
    Posts:
    2
    For toggles you can use OnClick event of EventTrigger component instead of OnValueChanged. It solved loop problem in my case.
     
    qmzunity, Danny-vda and perplex_bcn like this.
  7. _Daniel_

    _Daniel_

    Joined:
    Feb 28, 2007
    Posts:
    2,555
    Same problem here. I need to update a slider's value based on a movie's playback position. I would prefer not getting an OnValueChanged event when I change the slider's value through code. Only when the user changes it by dragging the thumb, should the event be fired.
     
    rakkarage likes this.
  8. rakkarage

    rakkarage

    Joined:
    Feb 3, 2014
    Posts:
    619
    Same. i have a slider onValueChange that changes when i change the value from code

    i would like and expect onValueChange to happen only when the user changes the value not when i do in code

    as a workaround i have to wrap all my value access with an ignore bool flag and check that in the scroll change handler
     
    _Daniel_ likes this.
  9. _Daniel_

    _Daniel_

    Joined:
    Feb 28, 2007
    Posts:
    2,555
    Another workaround that I just implemented is to instead of modifying the value that the slider represents, actually manipulate the slider instead. For instance, lets say you want a slider to represent music volume. But other things manipulate the volume as well (e.g. PlayerPrefs). Have them all go through the slider to change the volume, nothing changes the volume directly. The ONLY thing that accesses the volume is the slider, period. So it would go like this:

    PlayerPrefs -> Slider -> Volume
    Human -> Slider -> Volume

    instead of:

    PlayerPrefs -> Volume
    Human -> Slider -> Volume
     
  10. jhorneman

    jhorneman

    Joined:
    Feb 27, 2014
    Posts:
    4
    This basically means you cannot do a Model View Controller architecture using the new UI system without adding quite ugly code (I am currently writing said ugly code). If you cannot change a control's state without triggering the entire UI logic, then the authoritative state is stored inside the UI control (so, the View), and not inside the Model.

    I have player option data which is loaded from PlayerPrefs, and I need to set the player option UI to reflect that data. There is no way around this, and every game with any kind of options must surely do this, and run into this exact same problem.

    When I set the UI control's state, that forcibly triggers the same logic as if the player had clicked on it. Which in my case means that initializing the player option UI does the same thing as if the player clicks every single control, which is problematic in my case.

    I now have to implement "React to this button except when this flag says we're initializing the UI" logic. The solution by _Daniel_ above could work too, but it has its own drawbacks.

    *grumble*
     
  11. Mihalin

    Mihalin

    Joined:
    Jan 31, 2015
    Posts:
    6
    Same problem. I want to have ignoreEvents variable in every UI element for example
     
    Ramcat and rakkarage like this.
  12. hollisbrown

    hollisbrown

    Joined:
    Nov 24, 2014
    Posts:
    1
    I have a similar problem with the new UI. Working on an RTS-like game and want UI toggles to represent the states of units when they get selected. I wondered if there was a decent way to (re)set UI elements without triggering any functions.
     
  13. TimK_personal

    TimK_personal

    Joined:
    Jul 30, 2014
    Posts:
    18
    The thing that baffles me is if you look at the source for Toggle, in the (private) Set function that takes an argument dictating whether or not to send the callback, it does an early out if the value didn't change. So I'm not sure why this infinite loop problem occurs in the first place.

    Edit: Whoops, never mind. I see why that wouldn't solve the problem.
     
    Last edited: Mar 23, 2015
  14. jsr2k1

    jsr2k1

    Joined:
    Aug 11, 2010
    Posts:
    30
    In this case, I don't use the OnValueChanged methods.
    Instead, I implement the interface IPointerClickHandler in the class and then I use the method:
    public void OnPointerClick(PointerEventData data)
    This method is called only when the user clicks on the toggle and not when the value is changed by code.
     
    airespt and perplex_bcn like this.
  15. BEFaughnan

    BEFaughnan

    Joined:
    Oct 4, 2013
    Posts:
    9
    This would be super helpful.
     
  16. zyzyx

    zyzyx

    Joined:
    Jul 9, 2012
    Posts:
    214
    I hope this gets addressed soon.
     
  17. prestonmatterport

    prestonmatterport

    Joined:
    May 7, 2015
    Posts:
    28
    Senshi likes this.
  18. _Daniel_

    _Daniel_

    Joined:
    Feb 28, 2007
    Posts:
    2,555
    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.UI;
    3. using System.Reflection;
    4.  
    5. public static class UISetExtensions
    6. {
    7.     static MethodInfo toggleSetMethod;
    8.  
    9.     static UISetExtensions()
    10.     {
    11.         MethodInfo[] methods = typeof(Toggle).GetMethods(BindingFlags.NonPublic | BindingFlags.Instance);
    12.         for (var i = 0; i < methods.Length; i++)
    13.         {
    14.             if (methods[i].Name == "Set" && methods[i].GetParameters().Length == 2)
    15.             {
    16.                 toggleSetMethod = methods[i];
    17.                 break;
    18.             }
    19.         }
    20.     }
    21.     public static void Set(this Toggle instance, bool value, bool sendCallback)
    22.     {
    23.         toggleSetMethod.Invoke(instance, new object[] {value, sendCallback});
    24.     }
    25. }
    26.  
    :):)
     
  19. Senshi

    Senshi

    Joined:
    Oct 3, 2010
    Posts:
    516
    I'm not sure if this should count as reflection abuse or pure elegance, but either way I love it! Thanks for sharing! =)
     
    _Daniel_ likes this.
  20. _Daniel_

    _Daniel_

    Joined:
    Feb 28, 2007
    Posts:
    2,555
    Think of it as a temporary hack until unity introduces a proper solution.
     
  21. prestonmatterport

    prestonmatterport

    Joined:
    May 7, 2015
    Posts:
    28
    Wonderful, thank you!
     
    _Daniel_ likes this.
  22. _Daniel_

    _Daniel_

    Joined:
    Feb 28, 2007
    Posts:
    2,555
    There are some other UI components that have Set methods as well, such as Slider.
     
    dreasgrech likes this.
  23. dreasgrech

    dreasgrech

    Joined:
    Feb 9, 2013
    Posts:
    193
    I've added the Slider, Scrollbar and Dropdown types to the class (supports Unity 5.3 as well):
    Code (CSharp):
    1. using System.Reflection;
    2. using UnityEngine.UI;
    3.  
    4. /// <summary>
    5. /// http://forum.unity3d.com/threads/change-the-value-of-a-toggle-without-triggering-onvaluechanged.275056/#post-2348336
    6. ///
    7. /// Problem:
    8. ///     When setting a Unity UI Toggle field isOn, it automatically fires the onchanged event.
    9. ///
    10. /// This class allows you to set the Toggle, Slider, Scrollbar and Dropdown's value without invoking the onchanged event.
    11. /// It mostly does this by invoking the private method ('Set(value, sendCallback)') contained in some of the Unity UI elements
    12. /// </summary>
    13. public static class UISetExtensions
    14. {
    15.     private static readonly MethodInfo toggleSetMethod;
    16.     private static readonly MethodInfo sliderSetMethod;
    17.     private static readonly MethodInfo scrollbarSetMethod;
    18.  
    19.     private static readonly FieldInfo dropdownValueField;
    20.     private static readonly MethodInfo dropdownRefreshMethod;  // Unity 5.2 <= only
    21.  
    22.     static UISetExtensions()
    23.     {
    24.         // Find the Toggle's set method
    25.         toggleSetMethod = FindSetMethod(typeof (Toggle));
    26.  
    27.         // Find the Slider's set method
    28.         sliderSetMethod = FindSetMethod(typeof (Slider));
    29.  
    30.         // Find the Scrollbar's set method
    31.         scrollbarSetMethod = FindSetMethod(typeof (Scrollbar));
    32.  
    33.         // Find the Dropdown's value field and its' Refresh method
    34.         dropdownValueField = (typeof (Dropdown)).GetField("m_Value", BindingFlags.NonPublic | BindingFlags.Instance);
    35.         dropdownRefreshMethod = (typeof (Dropdown)).GetMethod("Refresh", BindingFlags.NonPublic | BindingFlags.Instance);  // Unity 5.2 <= only
    36.     }
    37.  
    38.     public static void Set(this Toggle instance, bool value, bool sendCallback = false)
    39.     {
    40.         toggleSetMethod.Invoke(instance, new object[] {value, sendCallback});
    41.     }
    42.  
    43.     public static void Set(this Slider instance, float value, bool sendCallback = false)
    44.     {
    45.         sliderSetMethod.Invoke(instance, new object[] {value, sendCallback});
    46.     }
    47.  
    48.     public static void Set(this Scrollbar instance, float value, bool sendCallback = false)
    49.     {
    50.         scrollbarSetMethod.Invoke(instance, new object[] {value, sendCallback});
    51.     }
    52.  
    53.     public static void Set(this Dropdown instance, int value)
    54.     {
    55.         dropdownValueField.SetValue(instance, value);
    56.         dropdownRefreshMethod.Invoke(instance, new object[] {}); // Unity 5.2 <= only
    57.  
    58.         /* In Unity v. 5.3 and above, they removed the private "Refresh" method and now instead you need to call instance.RefreshShownValue(); instead. */
    59.         // instance.RefreshShownValue(); // Unity 5.3 >= only
    60.     }
    61.  
    62.     private static MethodInfo FindSetMethod(System.Type objectType)
    63.     {
    64.         var methods = objectType.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance);
    65.         for (var i = 0; i < methods.Length; i++)
    66.         {
    67.             if (methods[i].Name == "Set" && methods[i].GetParameters().Length == 2)
    68.             {
    69.                 return methods[i];
    70.             }
    71.         }
    72.  
    73.         return null;
    74.     }
    75. }
    Usages:
    Code (CSharp):
    1. toggle.Set(true, false); // Set the value of the Toggle without raising the event
    2.  
    3. slider.Set(1f); // Set the value of the Slider without raising the event
    4.  
    5. scrollBar.Set(1f, true); // Set the value of the Scrollbar and raise the event
    6.  
    7. dropdown.Set(1); // Set the value of the Dropdown without raising the event
     
    Last edited: Dec 9, 2015
    LocDogg, Lysander, sergiobd and 5 others like this.
  24. inferno222

    inferno222

    Joined:
    Apr 29, 2014
    Posts:
    3
    There's another way around for this problem.
    (Only tested on toggles, though it should work for everything)

    1- create a function you want to activate with toggle
    2- create a function that receive as parameter a toggle
    (This function should check if toggle is interactable otherwise return, and then call first function)
    3- In the Toggle place the second function and pass the same toggle as parameter

    Now whenever you change the isOn you should set interactable to false first, then change it again(if needed)

    I know it doesn't seems clean but in my case it worked great.
    I hope someone else find this useful :D

    PD:
    In my case i passed more information through the toggle name
    Additionally you can check if isOn is true or false and call 2 different functions or something idk
     
  25. ThermalFusion

    ThermalFusion

    Joined:
    May 1, 2011
    Posts:
    766
    The things vented here was one of the main issues I had with our previous UI solution, I had hoped that this would not be the case with uGUI. I really hope the non callback set functionality will be exposed soon.
     
    zyzyx likes this.
  26. Sebioff

    Sebioff

    Joined:
    Dec 22, 2013
    Posts:
    171
    Another vote that this is required (for all UI components).
     
  27. CrazyRocksStudios

    CrazyRocksStudios

    Joined:
    Sep 29, 2015
    Posts:
    15
    I got super simple and super hacky workaround :)

    /////////////////

    Slider slider;
    public bool applySliderChange = true;
    public void OnSliderValueChanged()
    {
    if(!applySliderChange)
    {
    applySliderChange= true;
    return;
    }

    // slider change callback
    }

    /////////////////

    Now every time when You want to set ui slider value with no effect ( reserved only for manual changes )
    call

    applySliderChange = false;
    slider.value = [Some different value]

    I know, I know :)
    ( but it's working - If You have many controls, the code will grow tho .. )
     
    shegway likes this.
  28. Kailric

    Kailric

    Joined:
    Aug 12, 2015
    Posts:
    13
    I have just now encountered this problem. It took a while of debugging first just to figure out what the problem was. I am trying to load player preferences and have the toggles, sliders, etc all set to the correct value at game start. I used the boolean variable solution here except I use Awake and Start. On Awake I set setAwakeValues = true so the OnValueChange methods know not to change anything, then set all the GUI elements to the correct value. Then on Start method I set setAwakeValues = false so that the player can then change those.

    This works for when you want to simply load values at game start, but wouldn't work during play obviously.

    I vote for an official fix. :)
     
  29. airespt

    airespt

    Joined:
    Apr 7, 2016
    Posts:
    1
    Indeed, I was having issues with uncertain triggering on DropDown.onValueChanged event.

    Although unity docs clearly states: this event is triggered "...when a user has clicked one of the options..." in http://docs.unity3d.com/ScriptReference/UI.Dropdown-onValueChanged.html

    Using 5.3.4 (64bit), after digging into unity docs, found this gem in http://docs.unity3d.com/ScriptReference/UI.Dropdown.DropdownEvent.html

    (JS)
    my_dropdown.onValueChanged.SetPersistentListenerState(0, Events.UnityEventCallState.Off);
    my_dropdown.value = newValue;
    my_dropdown.onValueChanged.SetPersistentListenerState(0, Events.UnityEventCallState.RuntimeOnly);

    No boolean flags, no reflection, cleaner I guess.
     
    rakkarage likes this.
  30. virror

    virror

    Joined:
    Feb 3, 2012
    Posts:
    2,957
    Brilliant!
     
  31. williamcwlee

    williamcwlee

    Joined:
    Sep 3, 2015
    Posts:
    1
    I have another solution. This is what I did: Make a duplicated slider bar just below* the original slider bar on the hierarchy (same position overlapping the old bar), next make the new bar invisible (drag all color A in the RGBA value to the left) so user will only see the old bar. As video plays the old bar will change position base on the position of the video. Only assign on value change methods to the new bar. The end result is, as I drag the bar using my hand (I am actually dragging the new invisible bar), the video position will update according to the new bar value, and the old bar will also update according to the position of video.

    Almost no coding required, just some sneaky work around on the game objects.

    *Below because you want the invisible bar to be on top of the old bar so you can drag it
     
    Last edited: Jul 26, 2016
    joshmccready likes this.
  32. floky

    floky

    Joined:
    Oct 6, 2010
    Posts:
    230
    Although a bit late to the party, it seems Unity still doesn't have a better way to change the value of an UI component without triggering the "OnValueChanged" event.
    Using "SetPersistentListenerState" method described above involves a bit more work if you have more event listeners registered or if you have some that are triggered in editor only and others at runtime then you have extra work of restoring them back to their initial setting.

    So I'll just pitch my approach to this below:

    Code (CSharp):
    1.  
    2.         // Backup reference to the current event object.
    3.         var backupEvent = dropdownComponent.onValueChanged;
    4.         // Create new temporary empty one (can be cached to avoid too much GC)
    5.         dropdownComponent.onValueChanged = new Dropdown.DropdownEvent();
    6.  
    7.         // Apply the change from code
    8.         dropdownComponent.value = selectedIdx;
    9.         dropdownComponent.RefreshShownValue();
    10.  
    11.         // Restore the original event reference.
    12.         dropdownComponent.onValueChanged = backupEvent;
    13.  
    Of course the above can be made a bit more elegant and generic using extension methods but this is the core idea.
     
    Last edited: Aug 12, 2016
  33. _Daniel_

    _Daniel_

    Joined:
    Feb 28, 2007
    Posts:
    2,555
    Have you tested it? Does it work?
     
  34. floky

    floky

    Joined:
    Oct 6, 2010
    Posts:
    230
    Sure! Tested and works.
    It shouldn't have any reason to not work as long as we have read-write access to the "OnValueChanged" event.
    Cheers! ;)
     
    _Daniel_ likes this.
  35. _Daniel_

    _Daniel_

    Joined:
    Feb 28, 2007
    Posts:
    2,555
    I'm liking your approach best right now, thanks for sharing.
     
  36. IzzySoft

    IzzySoft

    Joined:
    Feb 11, 2013
    Posts:
    376
    i wonder if you could set it to null?
    ex:
    Code (csharp):
    1.  
    2. // Create new temporary empty one (can be cached to avoid too much GC)
    3. //dropdownComponent.onValueChanged = new Dropdown.DropdownEvent();
    4. dropdownComponent.onValueChanged = null;
    5.  
     
  37. _Daniel_

    _Daniel_

    Joined:
    Feb 28, 2007
    Posts:
    2,555
    Nope, Unity throws an exception. See attachment for details.
     

    Attached Files:

  38. _Daniel_

    _Daniel_

    Joined:
    Feb 28, 2007
    Posts:
    2,555
    This is what I've got so far. Feel free to expand upon or improve.
    Code (CSharp):
    1. public static class UIEventSyncExtensions
    2. {
    3.     static Slider.SliderEvent emptySliderEvent = new Slider.SliderEvent();
    4.     public static void SetValue(this Slider instance, float value)
    5.     {
    6.         var originalEvent = instance.onValueChanged;
    7.         instance.onValueChanged = emptySliderEvent;
    8.         instance.value = value;
    9.         instance.onValueChanged = originalEvent;
    10.     }
    11.  
    12.     static Toggle.ToggleEvent emptyToggleEvent = new Toggle.ToggleEvent();
    13.     public static void SetValue(this Toggle instance, bool value)
    14.     {
    15.         var originalEvent = instance.onValueChanged;
    16.         instance.onValueChanged = emptyToggleEvent;
    17.         instance.isOn = value;
    18.         instance.onValueChanged = originalEvent;
    19.     }
    20.  
    21.     static InputField.OnChangeEvent emptyInputFieldEvent = new InputField.OnChangeEvent();
    22.     public static void SetValue(this InputField instance, string value)
    23.     {
    24.         var originalEvent = instance.onValueChanged;
    25.         instance.onValueChanged = emptyInputFieldEvent;
    26.         instance.text = value;
    27.         instance.onValueChanged = originalEvent;
    28.     }
    29.  
    30.     // TODO: Add more UI types here.
    31. }
    32.  
     
    Hadrien, Hs_Jack, NavidK0 and 6 others like this.
  39. floky

    floky

    Joined:
    Oct 6, 2010
    Posts:
    230
    Glad to help! ;)
     
  40. MrScrumbles001

    MrScrumbles001

    Joined:
    Jun 7, 2013
    Posts:
    18
    A simple hackey solution is to just have a bool set to false when you don't want to trigger the rest of the OnValueChanged script. Just make sure to set it to true again :)
     
  41. aschuetzer

    aschuetzer

    Joined:
    Nov 21, 2016
    Posts:
    3
    I found a solution that do not allow the OnValueChange to do something if there was no interaction with UI.
    You simple should place this on the begin of triggered function:
    Code (CSharp):
    1.      
    2. Toggle clickedToggle = UnityEngine.EventSystems.EventSystem.current.currentSelectedGameObject.GetComponent<Toggle>();
    3. if(clickedToggle == null) {
    4.   return;
    5. }
    6.  
    This code will check if the user clicked the toggle and if he doesn't leave function :)
     
    Emperor, imphy and rakkarage like this.
  42. FireHawkX

    FireHawkX

    Joined:
    Apr 26, 2016
    Posts:
    13
    I cannot for the life of me understand how this is still not fixed in 2017!! this thread was started in 2014!!

    No wonders most games done using Unity have very basic if any option menu...

    Sorry to bother you Daniel, but I'd like to understand how to use your solution... do I simply copy paste all the code you created in a new CS file in my project? How do I escape the "on value changed" events that are auto called whenever i change a value (isOn, or any other manually)?

    I understand the simple "hacky" version of (CrazyRocksStudios) and will most likely try to do that tomorrow... but it still pisses me off that something so basic is still missing from Unity after all those years...

    Thanks all who contributed! Hope this gets improved one day! :)
     
  43. Damon117

    Damon117

    Joined:
    Nov 4, 2015
    Posts:
    3
    What I'm doing is:


    Slider.SliderEvent onValueChanged = slider.onValueChanged;
    slider.onValueChanged = new Slider.SliderEvent();

    // your value changed code here

    slider.onValueChanged = onValueChanged;
     
  44. hantengx

    hantengx

    Joined:
    Mar 13, 2017
    Posts:
    7
    I think we can listen event Pointer click
    upload_2017-4-24_18-27-35.png
     
  45. Mark-Sweeney

    Mark-Sweeney

    Joined:
    Feb 21, 2010
    Posts:
    167
    Thank you! This worked perfectly for me. I'm using a slider as a playhead position, so naturally the OnValueChanged was called every time the position was updated with the current playhead time.
     
  46. Jayme65

    Jayme65

    Joined:
    Dec 11, 2016
    Posts:
    68
    How do I please use this to override the standard behavior of my toogle?
    Do I have to place this code on the same script that manage my toggle?
    Let's say that I have a toggle named 'tgl', how do I set its value?
    Thanks!
     
  47. _Daniel_

    _Daniel_

    Joined:
    Feb 28, 2007
    Posts:
    2,555
    Think of that script as a library. You write MonoBehavious that use it.
     
  48. Mark-Sweeney

    Mark-Sweeney

    Joined:
    Feb 21, 2010
    Posts:
    167
    Normally, you'd set that value of a toggle with:

    tgl.value = boolean;

    but that will trigger an OnValueChanged.

    However, with the UIEventSyncExtensions.cs script you have, you use:

    tgl.SetValue(boolean);

    where you'd normally use "tgl.value = boolean;"


    For a Slider you'd use:

    sliderName.SetValue(float);


    For a input field you'd use:

    inputfieldName.SetValue(string);
     
  49. andyz

    andyz

    Joined:
    Jan 5, 2010
    Posts:
    828
    Nice one Mark, but...

    Hey 2018 checking in - seems still no way to set a toggle state etc. without triggering a callback!
    What you up to Unity?!
     
  50. Hadrien

    Hadrien

    Joined:
    Sep 7, 2013
    Posts:
    25
    Awesome, works like a charm. Thank you Daniel!

    If someone is interested I added the Dropdown type to the code:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5.  
    6. public static class UIEventSyncExtensions
    7. {
    8.     static Slider.SliderEvent emptySliderEvent = new Slider.SliderEvent();
    9.     public static void SetValue(this Slider instance, float value)
    10.     {
    11.         var originalEvent = instance.onValueChanged;
    12.         instance.onValueChanged = emptySliderEvent;
    13.         instance.value = value;
    14.         instance.onValueChanged = originalEvent;
    15.     }
    16.  
    17.     static Toggle.ToggleEvent emptyToggleEvent = new Toggle.ToggleEvent();
    18.     public static void SetValue(this Toggle instance, bool value)
    19.     {
    20.         var originalEvent = instance.onValueChanged;
    21.         instance.onValueChanged = emptyToggleEvent;
    22.         instance.isOn = value;
    23.         instance.onValueChanged = originalEvent;
    24.     }
    25.  
    26.     static InputField.OnChangeEvent emptyInputFieldEvent = new InputField.OnChangeEvent();
    27.     public static void SetValue(this InputField instance, string value)
    28.     {
    29.         var originalEvent = instance.onValueChanged;
    30.         instance.onValueChanged = emptyInputFieldEvent;
    31.         instance.text = value;
    32.         instance.onValueChanged = originalEvent;
    33.     }
    34.  
    35.     static Dropdown.DropdownEvent emptyDropdownFieldEvent = new Dropdown.DropdownEvent();
    36.     public static void SetValue(this Dropdown instance, int value)
    37.     {
    38.         var originalEvent = instance.onValueChanged;
    39.         instance.onValueChanged = emptyDropdownFieldEvent;
    40.         instance.value = value;
    41.         instance.onValueChanged = originalEvent;
    42.     }
    43.  
    44.     // TODO: Add more UI types here.
    45.  
    46. }
     
    anthonykwinters likes this.