- Home /
Is it a bad idea to add and remove listeners for toggles and buttons at runtime?
Hello!
I'm working on a project which has many Toggles and Buttons.
I've found myself several times needing to change the state of a toggle, but without calling onValueChanged
. It just occurred to me that on these cases I could do myToggle.onValueChanged.RemoveAllListeners()
, then do the state change, and then re-add the listener to my toggle (all of these toggles only have one listener). This seems like the way to go, but I'm wondering if adding and removing listeners at runtime will have an impact on performance which will outweigh the gain. Any insights on this would be greatly appreciated. Thanks!
Answer by Hellium · Aug 10, 2021 at 03:33 PM
Can' you just call myToggle.SetIsOnWithoutNotify
?
https://docs.unity3d.com/2019.1/Documentation/ScriptReference/UI.Toggle.SetIsOnWithoutNotify.html
I believe it has been introduced in 2019.1. I don't see anything in 2018.4.
Answer by Pangamini · Aug 10, 2021 at 03:36 PM
You can add and remove listeners on the fly, it's not somewhat specially expensive. I don't know how many are we talking, and if you say 'many', it could possibly mean that it adds up to a pretty expensive operation. The best approach would be simply to profile it and see how long does it take. Anyway, whenever I need to do something similar, eg. when I have multiple UI controls setting the same value, I usually just set some flag inside the first callback, to tell the other callbacks to skip. For example:
// consider this a pseudocode
Slider m_slider;
Input m_input;
bool m_ignoreCallback = false;
void OnSliderChanged(float value)
{
if(m_ignoreCallback)
return;
m_ignoreCallback = true;
try
{
m_input.text = value.ToString();
}
finally
{
m_ignoreCallback = false;
}
}
void OnInputChanged(string value)
{
if(m_ignoreCallback)
return;
m_ignoreCallback = true;
try
{
m_slider.value = float.Parse(value);
}
finally
{
m_ignoreCallback = false;
}
}