Cant replace/change material properties

Hi, I have object with 2 materials. I Want to temporarily disable the second one or replace it, make it transparent etc. Nothing worked so far. Yes I have double triple checked all names, variables, I do have “ColorInside” variable in the shadergraph for that material. I have written a test code with 2 different approaches, the debug log says “material replaced” and no errors but in fact it isnt.

    private MeshRenderer m_renderer;

    // Name of the material you want to turn off
    public string materialNameToTurnOff;

    // The replacement material
    public Material replacementMaterial;
    // Start is called before the first frame update
    void Start()
    {
        m_renderer = GetComponent<MeshRenderer>();

        m_renderer.materials[1].SetColor("ColorInside", new Color(0, 0, 0, 0));
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKey(KeyCode.Escape))
        {
            MaterialChange();
        }
    }

    private void MaterialChange()
    {
        // Iterate through all materials of the Renderer
        for (int i = 0; i < m_renderer.materials.Length; i++)
        {
            // Check if the material name matches
            if (m_renderer.materials[i].name == materialNameToTurnOff)
            {
                // Assign the replacement material to the renderer
                m_renderer.materials[i] = replacementMaterial;

                Debug.Log("Material replaced.");

                break; // Stop searching once the material is found
            }
            else
            {
                Debug.Log("IS NOT WORK");
            }
        }
    }
3 Likes

To further explain Spy-Master’s link to the docs:

Generally accessing .material / .materials is going to give you a fresh copy. (See docs for why and when)

https://discussions.unity.com/t/789181/5

https://discussions.unity.com/t/826696/5

3 Likes

Ahh well, I never knew about that. All good and working now, thanks guys. I kinda understand now. That was great help.