- Home /
Change the Material of a Sprite with C#
I am looking for a way to change the material of a sprite during runtime. I have created a material called Ghost and placed it in an asset file called Shader. Changing the material works just fine when I manually change it to Ghost. But I can't get it to work through scripting. Currently I have
public class Stats : MonoBehaviour {
public int hitPoints;
public int strength;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
//Material mat = Resources.Load
//Debug.Log(mat);
//Debug.Log(GetComponentInParent<Renderer>().sharedMaterial);
if (hitPoints <= 0) {
if (GetComponentInParent<Transform>().tag == "Player") {
GetComponentInParent<Renderer>().material = Resources.Load<Material>("Ghost");
}
}
}
}
When the material should switch, it change the sprite to just a pink block.
Answer by HarshadK · Dec 29, 2014 at 11:15 AM
I have created a material called Ghost and placed it in an asset file called Shader.
Your Ghost material should be inside the Resources folder since you are using:
Resources.Load<Material>("Ghost");
in your script to load the Ghost material. Here script tries to load the Ghost material from Resources folder but there isn't any so no material is assigned.
Thank you for the explination on why that isn't working. Is there a way I can change the material to the Ghost material? Or would just moving the Ghost material to the Resources folder be the best option? (I don't know how to refer to the Ghost material with C#)
$$anonymous$$ove your Ghost material to the Resources folder.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Sprite obstruction transparent area 1 Answer
Created Material Shows Dark Sprite 1 Answer