UI RectTransform.rect.width/heigth returns incorrect/negative values
I am tryin to make simple HP bar, using two images - bacground is static and HP bar is interactively changing via C# on my object. But I can't correctly set/get values from rect because "width"/"height" and .sizeDelta returns me something like 3.0518e-05. There is fragment of code and couple screenshots:
void UpdateHPBar ()
{
//Debug string showing me 3.0518e-05, same with hpBar.rect.width
Debug.Log("Rect width: " + hpBar.sizeDelta.x.ToString());
//Next following two variants, both of them are not working
hpBar.sizeDelta = new Vector2(parent.sizeDelta.x * (health / maxHealth), hpBar.sizeDelta.y);
hpBar.SetSizeWithCurrentAnchors (RectTransform.Axis.Horizontal, 300 * ((float)health / (float)maxHealth));
}
There is many questions like this and I see no proper answers. Is it just a bug of the new UI?
3.0e-5 is just 0.00003, which is just 0 plus a rounding error.
For RectTransforms, width and height are only width and height for some settings. For others (something with anchor, or ... it's been a while) they mean the change from the parent(?) size. The manual barely explains it, haven't seen it well-explained anywhere else, and it is confusing, but it does work if you figure it out.
Of course I've read manual, but still can't figure out how to correctly change the size of RectTransform via scripts. Every way described on forums became useless with no reasons, things just not working or giving wrong result as like 0 size or errors ins$$anonymous$$d of changing size to 1/3 of some value.
Your answer
Follow this Question
Related Questions
RectTransform Left Right Bottom Top 0 Answers
Level Selector - Level Images for Brick Breaker 2 Answers
How to offset a RectTransform? 0 Answers
Scaling an image sent to UI Image 0 Answers