- Home /
How to change width and color of a 2d sprite within script
To make a health bar above enemies - I am using a white sprite that I colored to green, to size and put it as a child of the enemy. When the enemy gets attacked I will call ChangeHealthBar from another script.
I need in that function to change the boxes width and color - how would I do this?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyHealthBar : MonoBehaviour {
private HurtEnemy hurtEnemy;
private EnemyHealthManager enemyHealthManager;
public float scaleFactor;
// Use this for initialization
void Start () {
hurtEnemy = gameObject.GetComponent<HurtEnemy>();
enemyHealthManager = gameObject.GetComponent<EnemyHealthManager>();
}
// Update is called once per frame
void Update () {
scaleFactor = hurtEnemy.damageToGive / enemyHealthManager.CurrentHealth;
}
public void ChangeHealthBar(float scaleFactor) //need to add color arguement
{
//Need to change box width and color
//transform.localScale = Vector3(scaleFactor, scaleFactor, 1);
}
}
*whitespace is off because i don't know how to format on this website
Answer by knorke · Oct 02, 2017 at 08:14 AM
Actually thats fairly simple you just have to work with the component itself:
Let's say your sprite is called "healthBar"
public GameObject healthBar;
public Sprite anySprite;
public Vector3 anyWidth;
// Change sprite
healthBar.GetComponent<SpriteRenderer>().sprite = anySprite;
// change width
healthBar.transform.localScale = anyWidth;
You might want to change localScale to lossyScale. Any values can be modified in the Inspector.
Hope that helps you.
Your answer
![](https://koobas.hobune.stream/wayback/20220612140109im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Hiding system,loot system and enemy field of view 0 Answers
How to make sounds louder if I go faster 1 Answer
I need to move a sprite when an UI button is clicked 1 Answer