Home > Mobile >  Get every Button with a certain tag
Get every Button with a certain tag

Time:11-05

I am trying to change the color of all the buttons of a "pagination" when I click on one of them. So I tagged these buttons PageButton

Usually, I use FindGameObjectsWithTag to get a collection of elements with a certain tag. But even by casting it as Button It doesn't work/show an error and I don't find anything else than FindGameObjectsWithTag in the suggestion nor in the doc

private Button[] buttons;

void Start()
{
    //this show me an error telling me I can't convert form UI to gameobject
    buttons = GameObject.FindGameObjectsWithTag("PageButton") as Button;

    foreach(Button button in buttons)
    {
        //my code to change every buttons color will go here
    }
}

CodePudding user response:

You can't simply cast GameObject to Button. You need to use GetComponent!

You could either do it straight forward and use

var objs = GameObject.FindGameObjectsWithTag("PageButton");
buttons = new Button[objs.Length];
for(var i = 0; i < objs.Length; i  )
{
    buttons[i] = objs[i].GetComponent<Button>();
}

or use Linq Select and do

using System.Linq;

...

buttons = GameObject.FindGameObjectsWithTag("PageButton").Select(obj => obj.GetComponent<Button>()).ToArray();

Alternatively you could also go the other way round and find all Buttons in the scene using FindObjectsOfType and then filter by the tag like e.g.

var allButtons = FindObjectsOfType<Button>();
var taggedButtons = new List<Button>();
foreach(var button in allButtons)
{
    if(button.CompareTag("PageButton"))
    {
       taggedButtons.Add(button);
    }
}
buttons = taggedbuttons.ToArray();

again you could use Linq Where to shorten this

buttons = FindObjectsOfType<Button>().Where(button => button.CompareTag("PageButton")).ToArray();
  • Related