- Home /
How to get the spriterender default material in the code
Hi. I'd like to change the material of my spriterenderer if the player select a unit.
I created my shader, and my material.
So if I want to set the shader I simply add:
spriteRenderer.material = myMaterial;
How can I reset it to default material?
I tried by storing it afterhand by adding:
Material defaultSpriteMaterial = spriteRenderer.material;
spriteRenderer.material = myMaterial;
Then I would simply readd it after player deselects the unit. spriteRenderer.material = defaultMaterial;
But it is not working.
Is it possible to access the "Sprites_Default" material in other ways?
Answer by matmel · Aug 23, 2015 at 04:35 PM
Hi there. What about assigning the deafult material to an variable in editor. I mean something like this:
public Material deafultMaterial;
public Material yourMaterial;
Simply click on the circle on the right side of your instance in the inspector and add deafultmaterial to it. I think this is a easier way to reset the material and add yourMaterial:
void ResetMaterial()
{
GetComponent<SpriteRenderer>().material = deafultMaterioal;
}
void ChangeMaterial()
{
GetComponent<SpriteRenderer>().material = yourMaterial;
}
In that case I have to do the following: - Create the material (using the shader sprite-default) - $$anonymous$$anually assigning the material to each script, or add the material to a singleton and let all elements take it from there.
I'm currently doing that, but I was hoping to find a solution just via code, without adding any more materials.
Oh yes, i see. $$anonymous$$aybe you will find Shader.find usefull? Take a look, this allows you change a material under runtime http://docs.unity3d.com/ScriptReference/Shader.Find.html
You could also set default$$anonymous$$aterial to the material of the object on start
void Start()
{
default$$anonymous$$aterial = GetComponent<SpriteRenderer>().material;
}
Not sure why, but if I tried to get the material from the start (or from the awake, or anywhere else, before assigning it), it returns a non working material (all sprites become transparent).
I used the Shader Find and it works properly.
default$$anonymous$$at = new $$anonymous$$aterial(Shader.Find("Sprites/Default"));
Thank you very much!
YOU were the only one to have the information I need. Thankkkkk youuuuu!