Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get every Button with a certain tag

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
    }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading