- Home /
Instantiate a prefab at runtime
Instantiate a prefab at runtime give me a completely new copy of the original and it doesn't share the materials.
That error has been through before the release of Unity 3.0 and it's not fixed yet... I also load the prefab from resource folder and as long as it pass to another function, it always create a new instance different from original...
Answer by Bunny83 · Jun 26, 2011 at 03:06 AM
Prefabs are only an editor feature. At runtime there are no prefabs anymore. Only GameObjects! Those in your ressources folder aren't visible but they are there. Instantiate will always just clone the given object. Every renderer has it's own material instance. If you want to access the shared material use .sharedMaterial
. That's actually the one you assign in the inspector.
What you describe is not and have never been a bug / error.
Renderer.material:
"Modifying material will change the material for this object only."
Renderer.sharedMaterial:
"Modifying sharedMaterial will change the appearance of all objects using this material, and change material settings that are stored in the project too."
Answer by softready · Jun 27, 2011 at 02:21 AM
I think something wrong with that discussion. So what you basically mean is that the runtime instantiation will always create a new instance which doesn't share the material information with the original right? Imagine that when you create 100 bullets while shooting inside the scene and if it will add additional 100 drawcalls which can greatly affect the performance..
If the material is used by any other renderers, this will clone the shared material and start using it from now on.
When you instantiate a prefab, the instance will use the shared material. If you try to edit renderer.material on the instance, then the shared material is cloned and that clone is what will be edited.
Also, comments are not answers. Post comments as comments.
This is exactly what I need but in my problem, it doesn't work in that way. Every instantiated instances create their own instance of the material and they don't share each other.
How do you know that it's creating a clone of the shared material? Is it showing up in the Project panel? Are textures or materials being leaked?
Hi, I am creating the the GUI Quads which suppose to share the same material. Inside the Project panel, the created prefabs use the material name called (...(Clone) and when I change the properties of the clone material, other material doesn't change.. This testing clear my vision that the created prefabs doesn't share the same material
Note : I instantiate the prefab from the same class as I get the reference of the prefab and it works fine. It just doesn't work when I called the Instantiation from another class. $$anonymous$$ay be that's the bug.