- Home /
Nobody answers my question :/
Unity UI is very slow?!?
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
}
}
Answer by OncaLupe · Dec 06, 2015 at 08:16 PM
Are you updating the UI every frame? If you are, you should only update it when values change. Also, if you're using GetComponent every time, store the references and use those in updating.
Pasting your code would help to see if there is anything that could be done.
I paste some code, but I am not using GetComponent every frame. And I need to change the position every frame, because the enemies are constant moving and the health bar should follow them
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Unity UI slow?(WaitingForJob and Canvas.RenderOverlays related problem) 1 Answer
script runs fine on start up, but slows on second attempt 1 Answer
Request feedback for C# script (instantiating UI elements depending on Player Input) 0 Answers