- Home /
Setting sharedMaterial only setting for one object?
I'm trying to set materials when the game starts depending on the current platform. I have a bunch of objects sharing, let's say 'Steel' and for beefy platforms want to set it to 'Steel2'
I thought I could simply find one object using Steel, get it's renderer.sharedMaterial and assign to Steel2. This works fine, for one object. The rest are not affected, despite the explicit explanation that they should be in the Scripting Reference.
What am I missing?
Answer by Bunny83 · Jan 15, 2011 at 02:11 AM
You just changed the reference to point to another material. The sharedMaterial reference points to a Material within your assets. If you change this reference to another Material, the old Material isn't changed at all.
You could use
renderer.sharedMaterial.CopyPropertiesFromMaterial(mat1);
but watchout! that will change the material that is bound to this renderer and the old information is lost. If you plan something like that i would create 3 materials:
- That is used for the renderer and that is changed at runtime
- Your "Steal" material
- Your "Steel2" material
ps. the renderer.material is a local copy inside the renderer, if you change that the original material will not be changed.
*edit*15.01@04:00 Ok i've tested it with 2 spheres. Both have my "sharedMat". On one sphere i put this script (C#):
public class changeMat : MonoBehaviour
{
public Material Mat1;
public Material Mat2;
void OnGUI()
{
if(GUILayout.Button("Mat1"))
{
renderer.sharedMaterial.shader = Mat1.shader;
renderer.sharedMaterial.CopyPropertiesFromMaterial(Mat1);
}
if(GUILayout.Button("Mat2"))
{
renderer.sharedMaterial.shader = Mat2.shader;
renderer.sharedMaterial.CopyPropertiesFromMaterial(Mat2);
}
}
}
you have to assign the 2 different Materials to Mat1 and Mat2 in the editor. When you press one of the buttons the material get changed for both of my spheres and the sharedMat (that's the one i've assigned to the spheres) is changed (forever even when you stop the game).
That sounded like a good idea, but it's still not working, and now, I don't even get a change on the object found. I take it the documentation is wrong? I really want to avoid having to crawl my whole scene looking for materials to replace.
I just tried it, it works great for me ;) maybe something else is wrong. I just tried it with materials without texture, let me try this first. brb. ;)
I've tested it with textured and it works find. everything got copied except one thing: the used shader. That's why i copy the shader manually before i copy the properties in my example.
Setting the shader was the key. In fact, I didn't need to use CopyPropertiesFrom$$anonymous$$aterial after it. Thanks!
Spoke too soon. I ended up needing CopyProp... after all for more complex shaders. Anyway, all is well. I can have the same basic assets build for any platform, picking shaders/mats on-the-fly.