Rishi
Rishi

Reputation: 155

Using UnityEventTools.RemovePersistentListener

I am creating an editor script that creates UI buttons and add listeners with arguments. I have completed that. Now, I want to remove the listeners with code.

The unity documentation for this isn't much help.

Code:

GameObject my_UIPanel;

// Destroy panel and buttons that were created previously.

my_UIPanel = GameObject.Find ("Panel_RoomButtons");
Button[] myBtns = my_UIPanel.GetComponentsInChildren<Button> ();
foreach (Button myBtn in myBtns) 
{
    // This is the thing giving me a headache. Rest everything works fine.
    UnityEventTools.RemovePersistentListener(myBtn.onClick, myUIManager.DEV_myFunction); 
}
if (my_UIPanel != null) 
    DestroyImmediate (my_UIPanel);

// Create new panel and buttons.

my_UIPanel = Instantiate(Pnl_RoomBtnsPrefab) as GameObject;

foreach (GameObject emptyLocation in teleLocations) 
{
    GameObject myBtnGO = Instantiate (teleBtnPrefab) as GameObject;
    myBtnGO.name = emptyLocation.name + "Btn";
    myBtnGO.transform.SetParent (my_UIPanel.transform, false);
    GameObject currentGO = emptyLocation;
    Button myBtn = myBtnGO.GetComponent <Button> ();
    UnityEventTools.AddObjectPersistentListener(myBtn.onClick, myUIManager.DEV_myFunction, currentGO);
}

If you can help me solve this, I'd be grateful for your help.

Thanks!

EDIT: These are the errors I'm getting

Assets/Scripts/RIGScripts/Editor/WorkspaceSetupEditor.cs(247,65): error CS1502: The best overloaded method match for `UnityEditor.Events.UnityEventTools.RemovePersistentListener(UnityEngine.Events.UnityEventBase, int)' has some invalid arguments

Assets/Scripts/RIGScripts/Editor/WorkspaceSetupEditor.cs(247,65): error CS1503: Argument #2' cannot convertmethod group' expression to type `int'

in this line:

UnityEventTools.RemovePersistentListener(myBtn.onClick, myUIManager.DEV_myFunction);

Upvotes: 1

Views: 2553

Answers (3)

Carambaman
Carambaman

Reputation: 1

I was having the same problem.

Try this:

UnityEventTools.RemovePersistentListener<TYPE_OF_PARAMETER>(myBtn.onClick, myUIManager.DEV_myFunction);

This was the solution in my case :)

Upvotes: 0

Umair M
Umair M

Reputation: 10720

Try using specific class ButtonClickedEvent.

Remove Listeners:

myBtn.onClick.RemoveListener(methodName);

or

myBtn.onClick.RemoveAllListeners();

Add Listener:

myBtn.OnClick.AddListener(methodName);

Read More


UPDATE:

For Editor Mode:

try this:

UnityEventTools.AddPersistentListener(myBtn.onClick, new UnityAction(methodName));

Upvotes: 0

Rishi
Rishi

Reputation: 155

Well, I didn't realize this before. I got it to work.

UnityEventTools.RemovePersistentListener(myBtn.onClick, 0);

I was supposed to pass the index of the method and not the method name.

Thanks guys!

Upvotes: 1

Related Questions