You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

For循环内变量赋值异常:ComponentPos函数返回值不符合预期

运行时UI组件位置计算问题及解决方法

问题说明

我在测量运行时生成的UI组件高度,Height(i)始终返回100。预期ComponentPos函数返回-100*Index,但索引大于0时返回值一直是-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;
}

调试现象

通过Debug.Log调试发现,第0个和第1个组件高度均为100,但Pos值仅为-100,循环似乎只执行了一次减法操作。无论调用多少次该函数,索引大于0时返回值均为-100。

解决方案(由Ma3x提供)

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

附Height(i)函数代码

该函数用于获取UI组件的高度值:

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

内容的提问来源于stack exchange,提问作者Regina Apis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 13:57:20