Variable not being properly assigned inside of a for loop

Viewed 43

I'm measuring the height of UI components being generated during runtime. Height(i) only returns 100. So what it should return is -100 + Index. But for some reason, any index over 0 returns -100.

    public float ComponentPos (int Index) {
        float Pos = 0;
        Debug.Log(Index);
        for (int i = 0; i < Index; i++) {
            Pos = Pos - Height(i);
            Debug.Log(i + ": " + Height(i));
            Debug.Log("Pos: " + Pos);
        }
        
        return Pos;
    }

I debugged using Debug.Log, it shows that it counts the height of the 0th component and 1st component as 100. But then the value of Pos is only -100. I have no idea why it only does the subtraction once. The result is the same no matter how many times I call this function. Any index over 0 returns -100.

Console Output

Edit: Ma3x gave me a solution

 public float ComponentPos (int Index) {
        float Pos = 0;
        for (int i = 0; i < Index; i++) {
            float h = Height(i); 
            Pos = Pos - h;
        }        
        return Pos;
 }

Also here is the code for Height(i)

 public float Height(int Index) {
        return AbilityTypeWindows[AbilityType.text].GetChild(Index).GetComponent<RectTransform>().rect.height;
 }

It's very ugly and long, but basically it returns the height value of a UI component.

0 Answers
Related