How to call this method?

Any idea how I can make this work?

    private int max = 3;
    public Button b1;
    public Sprite sprite1;
    public Sprite sprite2;

    private void NewTurn()
    {
        b1.onClick.RemoveAllListeners();
       
        int randomNumber = Random.Range(1, max);
        b1.onClick.AddListener(Method/*Here should be the randomNumber*/());
        b1.GetComponent<Image>().sprite = sprite/*Here should bethe randomNumber*/;
    } 
    void Method1()
    {
        //This method will be called when the random number is 1.
    }
    void Method2()
    {
        //This method will be called when the random number is 2.
    }

The most obvious way is:

if (randomNumber == 1) add method2
if (randomNumber == 2) add method3```

Remember after that button is pressed, the listener will still be attached so if you call NewTurn again it will call both the old one and whatever new choice you choose.

It's usually more logically-appealing to set your button up identically ALWAYS(i.e., always call the same button function), then when pressed make a decision in the button responder what you want to do. It makes things a lot more centralized.
1 Like

I would consider setting up an Action that you can assign a method call to, and then just have one call you do from your button click that calls whatever method is assigned to the Action variable.

The other option is to consider… what is different between Method1 and Method2 as it’s possible you only need one method anyways that you can access a parameter int or a variable that is stored instead.

You will not be able to form a variable reference by adding a number onto a variable name (sprite + 1 for example), instead of doing that, consider a collection where you can access by index instead.

    private int max = 3;
    public Button b1;
    public Sprite sprite1;
    public Sprite sprite2;

    private void NewTurn()
    {
        b1.onClick.RemoveAllListeners();
     
        int randomNumber = Random.Range(1, max);
        switch (randomNumber)
        {
            case 1:
                Method1();
                break;
            case 2:
                Method2();
                break;
            default:
                //Put anything here you want just in case the number is other than 1 or 2 - maybe record something to the log
                break;
        }

        b1.onClick.AddListener(Method/*Here should be the randomNumber*/());
        b1.GetComponent<Image>().sprite = sprite/*Here should bethe randomNumber*/;
    }
    void Method1()
    {
        //This method will be called when the random number is 1.
    }
    void Method2()
    {
        //This method will be called when the random number is 2.
    }
1 Like