# Material not changing Unity3d [duplicate]

I have a MeshRenderer mr public variable in script1. I dragged mesh1 from the assets in the mr place in the inspector of script1. mesh1 has a material mat1, I try to change this material to mat2 using this mr.sharedMaterial = mat2; but the material doesn't change. It only changes the material in the assets but not the one in the hierarchy, so in the runtime nothing changes. Any advice please?

• I followed your steps. It works well. This is the script I assigned. // public class Test : MonoBehaviour { public MeshRenderer mr; public Material m2; void Awake(){ mr.sharedMaterial = m2;}} – Jinbom Heo Jun 4 '15 at 11:34
• @JinbomHeo thanks for your comment. In my case the material in the assets is the one that is changed not the one is the hierarchy. Although the one in the hierarchy is a result of dragging and dropping the one in the assets. – Tak Jun 4 '15 at 11:37

## 1 Answer

Ok, I see.

I think your GameObject is a prefab which can not modified in the runtime. So you can't apply the changes to other linked prefab objects in the runtime.

Only things that you can do is cloning and change the object's property respectively.

• thanks for your answer. Could you please tell me how to clone and change the object's property? I will upvote your answer anyway =) – Tak Jun 4 '15 at 11:58
• Ensure your MeshRenderer mr variable is pointing to the instance of the mesh renderer in the scene whose material you want to change, not to a prefab in your assets folder. You can create such an instance at runtime with the Instantiate() function. – DMGregory Jun 4 '15 at 14:09
• @DMGregory is right. that's the cloning what I meant. – Jinbom Heo Jun 4 '15 at 16:15
• @DMGregory but when I do Instantiate from the MeshRenderer mr, I find a new mesh appearing in different location in the scene :/ – Tak Jun 4 '15 at 17:03
• @shepherd: right, because Instantiate creates a new instance of the object. If you already have an instance in the scene, you want to point at that one. Try naming the scene instance something different from the prefab - eg if your prefab is called "MyMesh", call the instance of MyMesh in your scene hierarchy "MyMeshInstance" - this will make it easier to tell which version your script variable is pointing at. – DMGregory Jun 4 '15 at 17:08