How to make the function reusable of the button

Hi all

I have dynamically Created a 5 buttons.I have no problem with it. In this i have a 4 players. if i click for each button . It should identify the player and it should do function.

 using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class ButtonsProg : MonoBehaviour {
     public GameObject prefabButton;
     public RectTransform ParentPanel;
     public String k1="Player1",k2="Player2",k3="Player3";
     public String chooseplayer;
    public int playerselect;
    // Use this for initialization
     void Start () {
if(playerselect==1)
chooseplayer=k1;
if(playerselect==2)
chooseplayer=k2;
if(playerselect==3)
chooseplayer=k3;
           
         

    for(int i = 0; i < 5; i++)
         {
             GameObject goButton = (GameObject)Instantiate(prefabButton);
             goButton.transform.SetParent(ParentPanel, false);
             goButton.transform.localScale = new Vector3(1, 1, 1);
             Button tempButton = goButton.GetComponent<Button>();
             int tempInt = i;
             tempButton.onClick.AddListener(() => ButtonClicked(tempInt,chooseplayer));
         }
    
     }
     void ButtonClicked(int buttonNo,string Character)
     {
if(buttonNo==1 && Character=="player1")
Debug.Log("DO this functions");

if(buttonNo==2 && Character=="player1")
Debug.Log("DO this functions");

----
---
if(buttonNo==5 && Character=="player1")
Debug.Log("DO this functions");

for player2 function i have wrote like that.....


if(buttonNo==1 && Character=="player2")
Debug.Log("DO this functions");

if(buttonNo==2 && Character=="player2")
Debug.Log("DO this functions");

----
---
if(buttonNo==5 && Character=="player2")
Debug.Log("DO this functions");
     }

for player 3 i have written the same code...........
}


i think the code is too long. HOW TO REDUCE THE ABOVE CODE. How can i optimize the code.....


thanks in advace...

The problem is you’re trying to do multiple checks to do something.
if(buttonNo==5 && Character==“player2”)

Look for common things. In this case, Character.

so you could change this to

if(Character == "player2")
{
   switch(buttonNo)
   {
        case 1:
        case 2:
        etc...
   }
}

Now, this isn’t bad, but without knowing more of what “Do this function” is, this is the best I can offer. It may be that you just need to call a single function based on buttonNo and pass in the character so that you know who needs to be targetted. The main thing to consider is what is common.

When you write code, look at it and say, hey, this and this code are the same, what variables can I use to do something different so I can just reuse the code.