This is probably something simple but I can't figure it out. I am trying to change the material but it isn't working. What I am doing wrong? Code: Code (CSharp): void Start() { mat = GetComponent<Renderer>().material; Debug.Log("Start()" + " - mat: " + mat.ToString() + " - newMaterial: " + newMaterial.ToString()); } public void changeMaterial() { mat = newMaterial; Debug.Log("changeMaterial()" + " - mat: " + mat.ToString() + " - newMaterial: " + newMaterial.ToString()); } Log: Code (CSharp): Start() - mat: Black (Instance) (UnityEngine.Material) - newMaterial: Crystal_Blue_Mat (UnityEngine.Material) Log: Code (CSharp): changeMaterial() - mat: Crystal_Blue_Mat (UnityEngine.Material) - newMaterial: Crystal_Blue_Mat (UnityEngine.Material)
The script is attached to the object that I want to change the material. I am calling it when the player enters a trigger (box collider). As you can see from the debug log, the method is being accessed and the material values seem correct.
You're not actually updating the renderer's material. instead of this: Code (csharp): void Start() { mat = GetComponent<Renderer>().material; } public void changeMaterial() { mat = newMaterial; } do this: Code (csharp): Renderer myRenderer void Start() { myRenderer = GetComponent<Renderer>(); } public void changeMaterial() { myRenderer.material = newMaterial; }
This it is. I was about to write this, why did I hesitate? Oh well... @kdgalla Anyway, shouldn't this be considered a bug?
We can access the material with: Code (CSharp): mat = GetComponent<Renderer>().material; but we cannot act on it. To act on it, we must use: Code (CSharp): mat = GetComponent<Renderer>(); mat.material = newMaterial;
I think you misunderstand how C# reference types work. (Edit: actually the logic is the same whether it's a reference type or not.) in this case: mat = GetComponent<Renderer>().material; mat is a reference variable pointing to the Renderer's material. using mat, LumoKvin could have set any of the properties (i.e. color, mainTexture whatever) and it would have updated the renderer, because mat and GetComponent<Renderer>().material are both referencing the exact same material. That's not what LumoKvin did, though. Instead, he assigned mat to reference a different material, by typing mat = newMaterial; At that point, mat is no longer referencing the renderer's material, it is referencing a completely different material that has nothing to do with the render. So once you assign mat to a different material, it would not make any sense for it to update the render's material.