Home > Mobile >  How do i make sprite color depend on HP variable? (The less hp, the more red sprite should be)
How do i make sprite color depend on HP variable? (The less hp, the more red sprite should be)

Time:08-08

hierarchy

I have a ShootingEnemy object that includes img object (it has a SpriteRenderer on it). ShootingEnemy can be damaged by shooting it with player's bullets. I want it to become more and more red once its HP level drops. It means that when HP is 5, object has its standart sprite color, when hp is 4 color is a little bit red and when its 1 color is almost completely red I tried this code(on ShootingEnemy object):

void Awake() {
bullet = Resources.Load<Bullet>("Bullet");
rb = FindObjectOfType<Hero>().GetComponent<Rigidbody2D>();
sprite = GetComponentInChildren<SpriteRenderer>();
}
void Update() {
    sprite.color = new Color(255, 255f/5*hp, 255f/5*hp);
}

and even tried adding a script onto an img object:

public class ShootingEnemyChild : MonoBehaviour
{
    private int hp;
    private SpriteRenderer sprite;
    private ShootingEnemy parent;
    void Start()
    {
        sprite = GetComponent<SpriteRenderer>();
        parent = transform.parent.gameObject.GetComponent<ShootingEnemy>();

    }

    // Update is called once per frame
    void Update()
    {
        hp = parent.hp;
        sprite.color = new Color(255, (255/5)*hp, (255/5)*hp);
    }
}

It seems like object's animation doesnt let it change its color(probably, havent actually checked). when i tried changing color by myself before starting the game it still changed to its natural state, the same thing happened when i started a game and changed the color while it was paused.

Is this idea even realizable? if yes, how do i implement it into my game?

CodePudding user response:

Color takes in as arguments, that are floating point values in the range 0 to 1

sprite.color = new Color(1f, hp / 5f, hp / 5f);

A better way to do it is as follows:

sprite.color = Color.Lerp(Color.red, Color.green, hp / 5f);
  • Related