Not allowed to access Renderer.material on prefab object?

Im spawning tables, chairs and other objects from prefabs and I would like to change their color at runtime.

selectedMesh.GetComponent<MeshRenderer> ().material.color = colors [value];

But I get the error “Not allowed to access Renderer.material on prefab object. Use Renderer.sharedMaterial instead”

But I dont want to use sharedMaterial, since it changes the material for all the objects that share that material. I instead want to change the specific material of that single object.

Thanks for helping.

selectedMesh is not the object in the scene, meaning not an instantiated object. It’s the prefab itself you’re accessing, the one sitting in the project folder. Change that and it’ll work.

@Vulkanos_live
@wlzhang

With Instantiate(Cube, new Vector3(x, y, 0), Quaternion.identity);

You have to make that a gameobject (i.e. object “in the game itself”) by changing it to:

GameObject [whatever] = Instantiate(Cube, new Vector3(x, y, 0), Quaternion.identity) as GameObject;

THen under ChangeColor1(), say:

[whatever].GetComponent().material.color = Color.red;

That should work. Then its referencing the object that was instantiated, not the prefab it was instantiated from.

When you want to change color of a prefeb then you will use sharedMaterials.color instead of material.color

Example: selectedMesh.GetComponent ().sharedMaterials.color = colors [value];

I hope this will help