I have an object in my 2d game and I want the image rendered to differ depending on the value of an int (curHealth).
public class PlayerHealth : MonoBehaviour {
public int curHealth = 3;
private SpriteRenderer myRenderer;
public Sprite[] CookieLife;
void start (){
myRenderer = gameObject.GetComponent<SpriteRenderer>();
if (curHealth == 6) {
myRenderer.sprite = CookieLife[5];
}
if (curHealth == 5) {
myRenderer.sprite = CookieLife[4];
}
if (curHealth == 4) {
myRenderer.sprite = CookieLife[3];
}
if (curHealth == 3) {
myRenderer.sprite = CookieLife[2];
}
if (curHealth == 2) {
myRenderer.sprite = CookieLife[1];
}
if (curHealth == 1) {
myRenderer.sprite = CookieLife[0];
}
if (curHealth == 0) {
//destroy object and end game
}
}
}
I added the images (whom are from a sprite sheet) to the list through the inspector.
I am new to programming so looked around for what other people have done an made this piece of code, but I cannot get it to work - the console doesn’t show any errors, so I really have no idea what is wrong.
I looked at the following questions to get inspiration:
Change Texture2d of sprite within sprite renderer during runtime - Unity Answers and http://forum.unity3d.com/threads/mini-tutorial-on-changing-sprite-on-runtime.212619/