Script to change GameObject materials based on tag?

I’m looking to have a script that changes the material of all the GameObjects in the scene IF it has a tag set to equal “Primary”.

My code so far:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Test : MonoBehaviour {
	public GameObject test;
	public void changeColor(Material mat)
		if (test.CompareTag("Primary"))
		test.GetComponent<Renderer>().material = mat;

It works with only one GameObject that has to be preset in the Inspector. It does check for the Primary tag however. Is there anyway to skip the Inspector and have a script that changes the materials for all GameObjects assuming it matches the set tag? My goal is to have a script that changes the material of multiple GameObjects that have a set tag after a UI button is pressed.

I have a very limited scope of C#, so any help would be appreciated here. I’ve been stuck on this for 3 days. Can’t find many relevant tutorials on this either.

Good day.

You only need to look for all gameobjects in the scene with the tag you want. So you need to do a foreach, to make some change in all objects in a array of Objects. This array must be all objects in the scene with the tag. So you want this:

foreach ( GameObject ObjectFound in GameObject.FindObjectsWithTag("Primary"))
//Do something to ObjectFound, like this:
ObjectFound.GetComponent<Renderer>().material = mat;

So while executing, an array with all GameObjects with Tag(“Primary”) will be created, and will do this action for each object in this array.


@tormentoarmagedoom Where do I put your code into the script? Do I add the foreach line under a function or above like a public variable? Popping it into Unity is giving me errors and I’m not sure if I’m adding it into my script correctly.