0
\$\begingroup\$

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?

\$\endgroup\$
2
  • \$\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
    Commented Jun 4, 2015 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
    Commented Jun 4, 2015 at 11:37

1 Answer 1

1
\$\begingroup\$

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.

\$\endgroup\$
7
  • \$\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
    Commented Jun 4, 2015 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
    Commented Jun 4, 2015 at 14:09
  • \$\begingroup\$ @DMGregory is right. that's the cloning what I meant. \$\endgroup\$
    – Jinbom Heo
    Commented Jun 4, 2015 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
    Commented Jun 4, 2015 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
    Commented Jun 4, 2015 at 17:08

Not the answer you're looking for? Browse other questions tagged .