Change all material with custom tag

How would I change all the materials of an object with the same tag?
I tried something like:

            if(gameObject.tag == "mat"){
                //gameObject. = defaultMaterial;
                Debug.Log( "set default material");
            }

Thanks!

Probably by using this:

You should get a list of materials. Just edit those.

1 Like

Something like this (code not tested)
Fixed the code to match up @jeromeatunity version (direct access to renderer.materials dont work*)*
```csharp
*using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ChangeMaterialsByTag : MonoBehaviour
{
public Material defaultMaterial;

void Start()
{
    GameObject[] m_gameObjects = GameObject.FindGameObjectsWithTag("MakeRed");
    foreach (GameObject m_gameObject in m_gameObjects)
    {
        Renderer[] renderers = m_gameObject.GetComponentsInChildren<Renderer>();
        foreach (Renderer renderer in renderers)
        {
            int i = 0;
            Material[] m_materials = renderer.materials;
            foreach (Material material in renderer.materials)
            {
                m_materials[i++] = defaultMaterial;
            }
            renderer.materials = m_materials;
        }
    }
}

}*
```

1 Like

Building on the replies from @Dextozz and @Zer0Cool here is a sample script that should point you in the right direction!

hth.

using UnityEngine;

public class UpdateMaterialsWithTag : MonoBehaviour
{

    public Material newMaterial;
    public string tag;

    private void UpdateMaterials()
    {
       
        // If values are null, exit!
        if(string.IsNullOrEmpty(tag) || newMaterial == null) return;

        // Find all objects with the tag
        var gameObjects = GameObject.FindGameObjectsWithTag(tag);
       
        // iterate
        foreach (var go in gameObjects)
        {
           
            // check if there is a mesh renderer component
            if (go.TryGetComponent<MeshRenderer>(out var mr))
            {
                // grab the materials array
                var materials = mr.materials;
               
                // update all the materials in our array
                for (int i = 0; i < materials.Length; i++)
                {
                    materials[i] = newMaterial;
                }

                // Update the material array on the mesh renderer...
                // see docs: Note that like all arrays returned by Unity, this returns a copy of materials array.
                // If you want to change some materials in it, get the value, change an entry and set materials back.
                mr.materials = materials;
            }
        }
    }
   
   
    private void OnGUI()
    {
        if (GUILayout.Button("Update All Materials!"))
        {
            UpdateMaterials();
        }
    }
}

6086826–660783–UpdateMaterialsWithTag.cs (1.48 KB)

1 Like

Thanks a lot, guys, very helpful input here!