- Home /
changing sprites depending on int value
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: http://answers.unity3d.com/questions/578228/change-texture2d-of-sprite-within-sprite-renderer.html and http://forum.unity3d.com/threads/mini-tutorial-on-changing-sprite-on-runtime.212619/
Answer by $$anonymous$$ · May 17, 2015 at 12:00 PM
Your problem lies in the fact your running your code in Start instead of Update.
The start function executes once when you object "starts" up. Update executes once per frame.
Try changing the line:
void start (){
to
void Update(){
http://answers.unity3d.com/questions/10189/what-is-the-general-use-of-awake-start-update-fixe.html
Also using GetComponent is an expensive operation so you don't want to run this every frame! $$anonymous$$ake sure to do this in the start function and store the result in a variable
And a small optimization that may or may not apply:
You are using a variable health where the values can be: 6, 5, 4, 3, 2, 1, 0.
The indexes for your sprites are 5, 4, 3, 2, 1, 0.
Note that both are a consecutive list of numbers and the indexes are one less than the health (except when the hp is 0);
So you can change your code to be:
public void ChangeSprite()
{
if(curHealth == 0)
{
// Destroy gameObject here
}
else
{
// Change the sprite index to be one less than your health.
myRenderer.sprite = CookieLife[curHealth - 1];
}
}
Sorry if that got complicated. I know your new at this...
Your answer
Follow this Question
Related Questions
cutout animation in top down view 2d 1 Answer
Strange artifacts in builds 0 Answers
Texturing custom 2d sprite 0 Answers
Spawning sprite in for loop 1 Answer