Get all objects with component and add component

I am trying to find all the objects with the Button script on (the UI one), and add another component to them all, but FindObjectsOfType only works if you are using all the same object type, so Ill be able to find all the Buttons, but not add a component to them as it is finding the component and not the object.

I want to do something like this (visual example), but obviously that isn’t supported syntax, does anyone know how to find all objects of a type and add another component to them?

GameObject[] buttons = FindObjectsOfType(typeof(Button));

You could simply do

GameObject[] buttonObjs = FindObjectsOfType<Button>();

for(int i=0; i< buttonObjs.Length; i++)
{
    if(buttonObjs[i].GetComponent<MyComponent>() == null)
    {
        buttonObjs[i].gameObject.AddComponent<MyComponent>();
    }
}

but honestly you’re better off planning ahead and simply having all Buttons start with the script. enabling/disabling when needed. the first option is just bad coding practice.

1 Like

@JoshuaMcKenzie has the form of it right.

But FindObjectsOfType returns an array of objects, so the code will look slightly different.

This looks more along the lines of what I needed, but I am getting the same error I was getting before:
Cannot implicitly convert type UnityEngine.UI.Button[ ]' to UnityEngine.GameObject[ ]’

Something like this?

Button[] buttonObjs = FindObjectsOfType<Button>();

for(int i=0; i< buttonObjs.Length; i++)
{
    if(buttonObjs[i].GetComponent<MyComponent>() == null)
    {
        buttonObjs[i].gameObject.AddComponent<MyComponent>();
    }
}
1 Like