- Home /
Assigning sharedMaterial to object built at runtime
I'm creating a number of GameObjects at runtime using:
new GameObject ("NewObject");
and then creating its mesh (vertices, triangles, ...) and components in script. All this works fine, but I'm trying to figure out how to assign one shared material to all these objects. When changing for example the texture of this material, I want it to change in all the objects using this material (and hopefully save some drawcalls in the process).
I tried using:
object.renderer.sharedMaterial = material;
But that still seems to create a difference instance for each object?
Any help would be appreciated.
if you are trying to go with batching, would be really interesting. Subscribed to question
Answer by Adherbal · Aug 09, 2013 at 06:11 PM
I found the reason of my problem. After assigning a sharedMaterial I was doing
if (object.renderer.material.mainTexture.width > ...)
Apparently just referring to mainTexture is enough to "break" the sharedMaterial and create an instanced material instead.
So I changed it to:
if (object.renderer.sharedMaterial.mainTexture.width > ...)
Now changing the material's texture changes the appearance of all objects, as intended. However I did not get any saved drawcalls, but I'll look into that later.
Yep, i was checking if there was transparency in my material as..
public bool isOpaque {
get { return renderer.material.color.a == 1; }
}
ins$$anonymous$$d of..
public bool isOpaque {
get { return renderer.shared$$anonymous$$aterial.color.a == 1; }
}
and that was ruining batching.
yup I was just checking the name of the material and that was enough to create an instance. Thank you!!!
Answer by pitimoi · Aug 09, 2013 at 05:15 PM
Hi,
Try to asign the rendere.material instead of sharedMaterial. The 'material' variable is the material instance used during runtime.
Your answer
![](https://koobas.hobune.stream/wayback/20220613111842im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
grab all game objects with a distance of the object? 2 Answers
Assign gameObject to a variable at runtime 2 Answers
How to display my castle name at runtime 3 Answers
GameObject.Find vs Resources.Load 1 Answer
Getting a camera at runtime 1 Answer