Question by
bean-man · May 04, 2020 at 12:42 AM ·
guirecttransformbar
How to make a health bar with multiple fields along the same bar? ,
So I'm trying to add a health bar kind of thing to represent the number of people in each state. I've got it working a few times but it's never perfectly aligned, it breaks when changing canvas UI scale modes. Heres what it looks like with each value (when it kinda works)
But on some other values(like these) it isn't accurate and breaks
This is the code I've came up with:
// Width of the bar
public float barWidth;
// Declare Rawimage var objects
public RawImage[] states;
// Amount of people in each state
public float[] stateCount;
// Each states population divided
public float[] stateCountDivided;
// Total number of people
public float peopleCount;
void Update(){
// For all states except 0
for (int i = 1; i < states.Length; i++) {
// Set state of position relative to the last one
states[i].transform.position = new Vector2(states[i - 1].transform.position.x + (states[i - 1].GetComponent<RectTransform>().sizeDelta.x)* 2, states[0].transform.position.y);
}
// For all states
for (int i = 0; i < states.Length; i++){
// Find percentage of each states population
stateCountDivided[i] = (stateCount[i]/ peopleCount) * 100;
// Set Width position based on a percentage of stateCountDivided over the bar width
states[i].GetComponent<RectTransform>().sizeDelta = new Vector2((stateCountDivided[i] / barWidth) * 100, 19f);
}
}
So there are 5 rawimages. One for the background, then one for each of the four bars. The four bars are anchored to top left, and are all children to eachother so red is a child to green, blue is a child to red, purple is a child to blue.
I've spent an embarrassing length of time on trying to fix this so I'd appreciate any help, thanks!
,
Comment