0

I am trying to add an onClick event to a bunch of buttons on screen that I have Instantiated. But the function I am calling needs parameters. When I put the parameters the code doesn’t run but when I don’t it runs but the function doesn’t do what it is supposed to because it doesn’t have the right parameters. Any ideas?

public void PreviewButtonLook(Image previewPart, Sprite previewSprite) 
{
   previewPart.GetComponent<Image>().sprite = previewSprite; 
}

button.GetComponent<Button>().onClick.AddListener(PreviewButtonLook(previewPart, options[i]);
Hank Helmers
  • 33
  • 1
  • 8

1 Answers1

2

onClick.AddListener() accepts a delegate of zero parameters.

You can create a zero-parameter anonymous function and pass it as a delegate.

This zero parameter anonymous function can call another function and pass it as many parameters as you want.

button.GetComponent<Button>().onClick.AddListener(delegate {
    PreviewButtonLook(previewPart, options[i]);
});

But be aware of function closure.

  • Thank you, so much! – Hank Helmers Dec 09 '19 at 15:28
  • 1
    simply as lambda expression: `button.GetComponent – derHugo Dec 09 '19 at 17:02
  • (Lambdas implicitly cast to delegates when the type is known, like it is here). – Draco18s no longer trusts SE Dec 09 '19 at 17:02
  • Thank you! I have heard a lot about lambda, here and from other people. Is it something that I should learn extensively? If so, any recommendations on how? – Hank Helmers Dec 09 '19 at 17:26
  • @Hankery Lambdas are very powerful expressions that allow you to simplify your code and make it more readable. Here's a primer: https://www.tutorialsteacher.com/linq/linq-lambda-expression – Draco18s no longer trusts SE Dec 09 '19 at 17:37
  • Thank you! I'll check that out. – Hank Helmers Dec 09 '19 at 18:07