unity set button addlistener with parameter code example

Example 1: unity onclick addlistener

public int index;  
private Button myselfButton;   

void Start()  
{      
  myselfButton = GetComponent<Button>();      
  myselfButton.onClick.AddListener(() => actionToMaterial(index));  
}   

void actionToMaterial(int idx)  
{      
  Debug.Log("change material to HIT  on material :  " + idx);  
}

void Destroy()
{
  myselfButton.onClick.RemoveListener(() => actionToMaterial(index));
}

Example 2: adding a function with a parameter to a button Unity

void Start ()
      {
          ButtonPre.onClick.AddListener(delegate{SwitchButtonHandler(0);});
          ButtonNext.onClick.AddListener(delegate{SwitchButtonHandler(1);});
      }
  
      void SwitchButtonHandler(int idx_)
      {
          //Here i want to know which button was Clicked.
          //or how to pass a param through addListener
      }

Tags:

Misc Example