Renderer.material.color not changing color of prefab

Hello everyone,

my use case if very simple: I want the color of an object to change when it is clicked. If the user clicks somewhere else, it gets deselected and the color switches back to the original one.
This already works with a cube for me by the simple code of:

activeObject.GetComponent<Renderer>().material.color = Color.red;

Now I was importing an .obj file to make a prefab out of the mesh. If I click on the imported .obj it consists of a gameobject, a mesh and also a Material. I dragged the import into the scene, added some other components e.g. a meshrenderer and made it a prefab. The prefab also has the script with the line above for color changing. Selecting and deselecting the object works, however the mesh remains white-ish instead of turning red when active.

In the inspector, I assigned a defaul material (instance) to the materials/Element0 of the meshRenderer component component. When I now click on my object, the materialin the inspector also turns red as seen on the little colored sphere displayed. However in game the object still is white.


What am I missing here? Thank you in advance!

Hi, what about changing the material of the object entirely. so activeObject.GetComponent().material. = . I suggest doing this as you won’t have any issues with the default material not having a colour that you can edit.

There will be different ways of achieving and solving this issue. This is just the simplest way I can explain a solution to this.

Cheers

Hi, i think i realise the problem: activeObject.GetComponent(Renderer).material = Mat should be changed to activeObject.GetComponent(MeshRenderer).material = Mat. Make sure that the material that you assign in the inspector has the colour red.

Please let me know if this causes any issues and I will see what I can do.
Cheers

I found out what the problem was and it probably is a real beginner’s mistake. By dragging the imported .obj into the scene I got an empty parent gameobject named like the model with the actual model attached as a child. From my code I was just changing the parent’s material.
I adapted my code to first get the child component and then set it’s material and everything works as expected now.