Search code examples
c#unity-game-enginegame-developmentrenderer

How to change material on second position?


I want to change material on position 2 , when i change material in my code it get changed on position 0 not on position 1.

I don't know how i can change material on position 1 .. This is code that changes material on position [0]

 public Material[] materials;
public Renderer rend;

// Start is called before the first frame update
void Start()
{
    rend= GetComponent<Renderer>();   
}
// Update is called once per frame
void Update()
{
 rend.material = materials[1];  
}

I want to change material on this picture with name New Material 2 To material which i define in code.

enter image description here

Thank you community very much :)


Solution

  • It changes on index 0 and not index 1 because you are using rend.material instead of rend.materials

    public class MaterialChanger : MonoBehaviour {
    
    public Material[] Materials;
    public MeshRenderer MeshRenderer;
    
    void Start() {
        MeshRenderer = gameObject.GetComponent<MeshRenderer>();        
    }
    
    void Update() {
        int requredMaterialIndex = 1; //this is just test value
        MeshRenderer.materials[1] = Materials[requredMaterialIndex];   
    }
    

    And I suggest you to always use Meshrenderer instead of Renderer just for efficiency