Home > Net >  Both slider keep listening when switch
Both slider keep listening when switch

Time:08-07

I use the bool value to set the slider to work, but when I set the bool to false, then switch to another bool value and reuse the slider again, both of the sliders work still listening not I switch one?

if (Bool[0]){
Sliderobj.GetComponent<Slider>().onValueChanged.AddListener((v) =>
  {
Debug.log("1")
  }}
if (Bool[1]){
Sliderobj.GetComponent<Slider>().onValueChanged.AddListener((v) =>
  {
Debug.log("2")
  }}

CodePudding user response:

You are adding a listener but not removing it. Also, don't keep adding and removing listeners based on the value of Bool[i], do this instead

Sliderobj.GetComponent<Slider>().onValueChanged.AddListener(delegate {
    HandleBoolValue(v);
});

void HandleBoolValue(var v) {
    if (Bool[0]) {
        Debug.Log("1");
    } else if (Bool[1]) {
        Debug.Log("2");
    }
}

CodePudding user response:

If you add a listener, then the only way to stop it to listen, is to remove the listener with the RemoveListener(listener) method.

If you are not keeping a reference to the listener delegate that you used when you called AddListener(...), then you can use RemoveAllListeners(), but this will remove all non-persisent (i.e. created from script) listeners from the event.

  • Related