# Renderer.material assignment not working [closed]

I have a fairly simple question: I am trying to change an object's material via code with the line

rend.material = NewMat;


where rend is of type Renderer (MeshRenderer to be specific) and NewMat is of type Material. Both variables are public and assigned in the inspector and both are not null.

When I now try to assign the material, nothing happens. I don't event get any error. When I look into the inspector I can see that under Materials on my MeshRenderer the material doesn't even change. The line

Debug.Log(rend.material == NewMat);


outputs false.

What am I doing wrong?

• It might be that you're not holding a reference to the renderer that you think you are. A common error is to write Instantiate(myPrefab); Renderer rend = myPrefab.GetComponent<Renderer>(); which gets the renderer on the prefab, not on the instance that you spawned. The comparison failing afterward could be because the .material getter copies the material and returns a new instance the first time it's called. We'd need to see more of your code in context to know for sure though - please edit the question to include a reproducible example. – DMGregory Aug 17 '18 at 14:33

Are you absolutely sure that you're using rend.material when trying to change the material?

I'm asking because, if you do something like this:

using UnityEngine;

public class ChangeMaterial : MonoBehaviour {
public Material NewMat;
public Material ObjMat;
public Renderer Rend;

private void Awake() {
Rend = GetComponent<Renderer>();
ObjMat = Rend.material;
}

private void Update() {
if (Input.GetKeyDown(KeyCode.Space)) {
ObjMat = NewMat;
}
}
}


the material won't change, but it will if you use:

private void Update() {
if (Input.GetKeyDown(KeyCode.Space)) {
Rend.material = NewMat;
}
}


(and note that in this case, ObjMat won't change in the Inspector, this is because ObjMat = Rend.material will pass the material by value and not by reference).

• Yes, I am directly trying to set the material on the renderer itself. – Jonas Kohl Jun 10 '18 at 19:03
• @JonasKohl then there must be something else that's happening, since that code should work. Can you post all the relevant code? Have you checked if somewhere else some code resets the material? – Galandil Jun 10 '18 at 20:38