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?

  • \$\begingroup\$ 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;}} \$\endgroup\$ – Jinbom Heo Jun 4 '15 at 11:34
  • \$\begingroup\$ @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. \$\endgroup\$ – Tak Jun 4 '15 at 11:37

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.

  • \$\begingroup\$ thanks for your answer. Could you please tell me how to clone and change the object's property? I will upvote your answer anyway =) \$\endgroup\$ – Tak Jun 4 '15 at 11:58
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ – DMGregory Jun 4 '15 at 14:09
  • \$\begingroup\$ @DMGregory is right. that's the cloning what I meant. \$\endgroup\$ – Jinbom Heo Jun 4 '15 at 16:15
  • \$\begingroup\$ @DMGregory but when I do Instantiate from the MeshRenderer mr, I find a new mesh appearing in different location in the scene :/ \$\endgroup\$ – Tak Jun 4 '15 at 17:03
  • 1
    \$\begingroup\$ @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. \$\endgroup\$ – DMGregory Jun 4 '15 at 17:08

Not the answer you're looking for? Browse other questions tagged or ask your own question.