- Home /
button remove listener
i have added a listener to a dynamically created gui button using the button.onClick.Addistener() function and that all works fine.
i am now trying to be able to remove listeners from the button but i am being unable to do so.
my code is:
void callTest()
{
RemoveListener(button,() => {callTest();});
Debug.Log("removing call from button");
}
public static void RemoveListener(Button button,UnityEngine.Events.UnityAction call)
{
button.onClick.RemoveListener(call);
}
The function is calling and then calling the static function, but then will not remove the listener as every time i click the button it recalls the initial function. it does work if i use button.onClick.RemoveAllListeners(); however this is not much help as it will remove all my listeners when i only need to remove one (only does something the first time, but continues to do the rest after) and don't want to re-add all the other functions every time it is clicked.
anyone have an idea why this will not be removing. useing the debugger shows no errors and that the correct function is being sent into the remove function
Thanks in advance
Answer by Hellium · Jun 29, 2015 at 10:51 AM
I advise you to take a look at the answer I gave to this question :
http://answers.unity3d.com/questions/993738/unityaction-vs-method.html
You will have to use delegates / UnityActions to keep a reference on the function you add to your listeners.
With the following line : RemoveListener(button,() => {callTest();});
, you try to remove a listener you are creating. In fact, () => {callTest();}
creates a new delegate. Thus, it hasn't the same reference as the one you have added before.
Thats great. I did not realise that it was creating a new delegate which does explain why it was not working.
$$anonymous$$odified from that post to store the action in a dictionary with the function name as a string as the key for reference purpose and this seams to be able to let me now remove them correctly
Thanks for the assist
Your answer
Follow this Question
Related Questions
How to get the GUI buttons to render properley 0 Answers
How to reflect / bounce audio off of a 3D Object? 4 Answers
AddListener to a Toggle. 1 Answer
Change the material of a buttons in List and keep it by draging around the screen? 2 Answers
Problem Displaying gameName when refreshing masterserver 0 Answers