Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question How to store anonymous method reference for future use?

Discussion in 'Scripting' started by chehob, Feb 15, 2021.

  1. chehob

    chehob

    Joined:
    Oct 25, 2017
    Posts:
    8
    Hello,

    This is the dynamic UI button creation from prefab example:
    Code (CSharp):
    1. private void CreateItemDisplay(MyItem item)
    2. {
    3.     var obj = Instantiate(ItemDisplayPrefab, ContentPanel);
    4.     obj.Button.onClick.AddListener(() => { OnItemClick(item); });
    5. }
    If at some other point in time I want to unsubscribe from onClick how can I remove the listener if I dont have a reference to this anonymous method?
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,722
    Code (CSharp):
    1. Action myListener = () => { OnItemClick(item); };
    Then use the "myListener" variable as desired.
     
    chehob and Kurt-Dekker like this.
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,756
    chehob and PraetorBlue like this.
  4. chehob

    chehob

    Joined:
    Oct 25, 2017
    Posts:
    8
    You mean I need to write it like this, if I have an array of these actions and want to store them for future use?
    Code (CSharp):
    1. private void CreateItemDisplay(MyItem item)
    2. {
    3.     var obj = Instantiate(ItemDisplayPrefab, ContentPanel);
    4.     UnityAction action = () => { var myItem = item; OnItemClick(myItem); };
    5.     obj.Button.onClick.AddListener(action);
    6.     itemClickActions.Add(obj, action);
    7. }