Unity Replacing a material at run time

16,799

Try this extension method

public static void ChangeMaterial(this GameObject go, Material mat)
{
    go.renderer.material = mat;
}

Then you can call it by using

if(hit.collider.gameObject.tag == "Colour1")
{
     hit.gameObject.renderer.material.ChangeMaterial( Your Material );
}

Here is another extension method for changing the color

public static void ChangeColor(this Material mat, Color color)
{
    mat.SetColor("_Color", color);      
}

Edit: Found my old extension method that supports multi materials on the gameObject

public static void ChangeColor(this GameObject go, Color color)
{
    if(go.GetComponent<MeshRenderer>())
    {               
        Material[] materials = go.gameObject.renderer.materials;

        foreach(Material m in materials)
        {
            m.SetColor("_Color", color);
        }   
    }
}

Finally to be more specific to your problem here is one final function for you

public static void ChangeColor(GameObject[] gameObjects, Color color)
{
    foreach(GameObject gameObject in GameObjects)
    {
        gameObject.renderer.material.ChangeColor( "Your Color" );
    }
}

then you can call it like this:

if(hit.collider.gameObject.tag == "Colour1")
{
    GameObject[] _Colums = GameObject.FindGameObjectsWithTag("column");
    ChangeColor(_Colums, "Your Color");
}
Share:
16,799
Sean
Author by

Sean

SOreadytohelp Stackoverflow has helped me develop and grow as a programmer. The knowledge I have gained from here and the code samples provided has helped me more times than I can mention. I'm not sure where I would be without stackoverflow SOreadytohelp

Updated on June 04, 2022

Comments

  • Sean
    Sean almost 2 years

    I'm trying to change the material of an object at run time based on a tag I've selected. However, instead of replacing the material, Unity is adding an instance of my target material and adding it to the object.

    Is there a way through code that I can delete the existing material and replace it with my targeted one?

    This is the code I have at the moment that deals with this:

    if(hit.collider.gameObject.tag == "Colour1")
    {
        GameObject[] _Colums = GameObject.FindGameObjectsWithTag("column");
        foreach( GameObject c in _Colums)
        c.renderer.material.color = hit.collider.gameObject.renderer.material.color;
    }
    
    • rutter
      rutter over 10 years
      Is this code executing while the game is editing, or while you're editing the scene?