Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Material Not Changing

Discussion in 'Scripting' started by Studio_Akiba, Feb 19, 2018.

  1. Studio_Akiba

    Studio_Akiba

    Joined:
    Mar 3, 2014
    Posts:
    1,421
    I have a script which is meant to change the material on a non-static object, but after it failing, and more testing on other objects, I cannot get it working at all on anything, yet I cannot see any problems with the code, can anyone see what I am doing wrong?

    I call MaterialIndex with an arg of 0, then Material with the new material, then ChangeMaterial with the object in question, and nothing changes, but they are being called (confirmed via Debug.Log).

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class ControlMaterials : MonoBehaviour
    6. {
    7.     public int materialIndex;
    8.  
    9.     public Material material;
    10.  
    11.     public void MaterialIndex(int value)
    12.     {
    13.         materialIndex = value;
    14.     }
    15.  
    16.     public void Material(Material value)
    17.     {
    18.         material = value;
    19.     }
    20.  
    21.     public void ChangeMaterial(GameObject target)
    22.     {
    23.         target.GetComponent<MeshRenderer>().materials[materialIndex] = material;
    24.     }
    25. }
     
  2. Rotary-Heart

    Rotary-Heart

    Joined:
    Dec 18, 2012
    Posts:
    813
    You cannot change it that way, you are changing a copy of the array. You need to do it this way:

    Code (CSharp):
    1. Renderer r = meshes[i].GetComponent<Renderer>();
    2. material[] mats = r.materials;  // copy of materials array.
    3. mats[n] = newMaterial; // set new material
    4. r.materials = mats; // assign updated array to materials array
    Note that this is literally a copy and paste from an old question you asked: https://forum.unity.com/threads/changing-material-array-via-c.436176/#post-2819823