For my game I have a health bar above the enemies made with UI panels. But when I enable this, my fps goes from 1000fps to 100-200fps(see the image). What is the reason, and how can I fix this?
This is my code to create a new health bar from prefab and keep it above the enemy(note that some variables are set from other scripts):
public RectTransform healthBar;
public RectTransform healthBarChild;
private int curHealth;
private int maxHealth;
private float maxScale;
private Vector3 offset;
private Transform canvas;
void Start()
{
canvas = Global.canvas;
healthBar = Instantiate(healthBarPrefab).GetComponent<RectTransform>();
healthBarChild = healthBar.GetChild(0).GetComponent<RectTransform>();
maxScale = healthBarChild.sizeDelta.x;
healthBar.SetParent(canvas);
}
void Update()
{
healthBar.position = Camera.main.WorldToScreenPoint(transform.position+ offset);
}
void onDamage(int damage) // is called when enemy gets damage
{
curHealth -= damage;
Vector2 curSize = healthBarChild.sizeDelta;
curSize.x = curHealth / (float)maxHealth * maxScale;
healthBarChild.sizeDelta = curSize;
if (curHealth <= 0)
{
die();//I didn't include this(and some other functions) as it is not necessary
}
}