Scaling related to damage

Hi everyone

(I am new to Unity, please keep that in mind, thank you)

Me and my friends are making a small 2D RPG-ish game. Currently I am trying to get our health bar to be reduced when the player character takes damage. To do this I have a red bar (health) and a black bar (depleted health), the black bar extends in one direction when the character takes damage, covering up the red bar. At the same time, a private integer named “health” counts down, and when it reaches zero, the game is over.

Here’s my problem:
If the player consumes a health potion, the health counter goes up and stops at a maximum. The health bar on the other hand, doesn’t. This means that if you consume a potion so that your health would exceed the maximum health value, the black bar extends past the red bar.

Looks like this

23134-bar.png
.

I have tried making an if-statement, but it didn’t work. I am guessing this is because I am using transform.localScale to scale the black bar.

Is there something obvious I’m missing with transform.localScale or should I just use some other scaling method? If the later, which one?

I’ll post my code as well, in case anyone would like to see it.

void OnTriggerEnter2D(Collider2D other)
	{
		if(other.tag =="Enemy")
		{
			health = health - 1;
			damage.transform.localScale += new Vector3(0.1f,0,0);
		}
	
		if(other.tag =="HealthPotion")
		{
			health = health + 7;
			damage.transform.localScale -= new Vector3(0.7f,0,0);
			if(health >= maxHealth)
			{
				health = maxHealth;
			}
			other.gameObject.SetActive(false);
		}

for your question, note that you scale your health outside of the if statement so it keep grow any way. you should do something like this:

health = health + 7;
if(health >= maxHealth)
     {
              health = maxHealth;
     }
    else
    {
    damage.transform.localScale -= new Vector3(0.7f,0,0);
    }

Add a vector3 variable called damageStart that holds the size of your damage bar when the game starts. Reset the bar to that size if the health is equal to maxHealth. Here is an example using compareTag instead of tag==:

public Vector3 damageStart;
	// Use this for initialization
	void Start () {
		damageStart = new Vector3(0.1f,0.5f,0.3f);
		damage.transform.localScale = damageStart;
	}
	

	void OnTriggerEnter(Collider other)
	{
		if(other.CompareTag("Enemy"))
		{

			health = health - 1;

			damage.transform.localScale += new Vector3(0.1f,0,0);
		}
		
		if(other.CompareTag("HealthPotion"))
		{

			health = health + 7;


			if(health >= maxHealth)
			{
				health = maxHealth;
				damage.transform.localScale = damageStart;
			}
			else
			{
				damage.transform.localScale -= new Vector3(0.7f,0,0);
			}
			other.gameObject.SetActive(false);
		}
}

HTH