【问题标题】:Iterate through a list on button press按下按钮时遍历列表
【发布时间】:2014-05-08 19:33:59
【问题描述】:

我的列表中有 3 个对象,但我只希望第一个元素处于活动状态。然后,当我按下一个按钮时,我希望列表向前移动一个,因此列表中的下一项现在处于活动状态,而第一项则不是。

我有以下代码:

void OnClick()
{
    for(int i = 0; i < activateTexture.Count; i++)
    {
        activateTexture[0].SetActive(true);
    }
}

这仅显示列表中的第一项(我想要的),但我一直在研究如何在列表中移动。

谁能帮帮我。

【问题讨论】:

    标签: c# list unity3d


    【解决方案1】:

    您将初始纹理设置为活动多次。相反,请跟踪当前的。然后,每次触发代码时,它都可以停用它所在的那个,然后移动到下一个并激活它。

    (下面过度注释的代码只是为了确保对这个答案进行了解释。我通常不会在我的代码中放置这样的 cmets)

    void Start()
    {
        // Initialize all textures to be inactive
        for(int i = 0; i < activateTexture.Count; i++)
        {
            activateTexture[i].SetActive(false);
        }
    
        // Activate the first texture
        activateTexture[0].SetActive(true);
    }
    
    // Store the index of the currently active texture
    private int activeTextureIndex = 0;
    
    void OnClick()
    {
        // Disable the current
        activateTexture[activeTextureIndex].SetActive(false);
    
        // Increment the index
        activeTextureIndex = (activeTextureIndex + 1) % activateTexture.Length;
    
        // Activate a texture based upon the new index
        activateTexture[activeTextureIndex].SetActive(true);
    }
    

    还请注意,我使用了模运算符 % 来循环列表。

    编辑:由于担心整数溢出而更正

    【讨论】:

      猜你喜欢
      • 2011-08-05
      • 2021-07-08
      • 1970-01-01
      • 1970-01-01
      • 2019-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-12
      相关资源
      最近更新 更多