代码之家  ›  专栏  ›  技术社区  ›  zyonneo

如何从Unity中的模型列表中实现下一个按钮和上一个按钮?

  •  -2
  • zyonneo  · 技术社区  · 7 年前

    我有一张10个型号的清单。最初我的场景中有一个模型,比如模型[0],当我单击“下一步”按钮时,它必须显示模型[1]到模型[9],同样,前一个按钮的顺序是相反的。

    我在代码中写了一个逻辑。我知道这不是一个标准的逻辑,但我相信它会完成我认为的工作。除了这个逻辑之外,还有任何简单的实现方法。

    public GameObject [] dress;
    
    public void PreviousModel()
    {
        int counter = dress.Length;//Dont know what to write here
        Debug.Log(counter);
        if(counter > -1)
        {
            counter--;
            dress[counter].SetActive(true);
            dress[counter+1].SetActive(false);
        }
    
    }
    
    public void NextModel()
    {
    
    
    }
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   derHugo    7 年前

    或者使用 Clamp 您还可以像

    public GameObject [] dress;
    
    private int _index;
    
    public void PreviousModel()
    {
        // Hide current model
        dress[index].SetActive(false);
    
        _index--;
        if(index < 0)
        {
            index = dress.Length -1;
        }
    
        // Show previous model
        dress[index].SetActive(true);
    }
    
    public void NextModel()
    {
        // Hide current model
        dress[index].SetActive(false);
    
        _index++;
    
        if(index > dress.Length -1)
        {
            index = 0;
        }
    
        // Show next model
        dress[index].SetActive(true);
    }
    

    所以在最后一个条目上单击Next,它将跳到第一个条目,而不是什么都不做。


    如果我理解你的意见

    索引值与场景中的模型相同

    正确地说,您的意思是,在该脚本开始时,需要根据当前活动的模型获取当前索引:

    private void Start()
    {
        // Get the index of the currently active object in the scene
        // Note: This only gets the first active object
        // so only one should be active at start
        // if none is found than 0 is used
        for(int i = 0; i < dress.Length; i++)
        {
            if(!dress[i].activeInHierachy) continue; 
    
            _index = i;
        }
    
    
        // Or use LinQ to do the same
        _index = dress.FirstOrDefault(d => d.activeInHierarchy);
    }
    
        2
  •  3
  •   Vampirasu    7 年前

    这应该会起作用的

    public GameObject [] dress;
    
        private int _index;
        public void PreviousModel()
        {
            _index = Mathf.Clamp(_index-1,0,9);
            // code to show your model dress[_index] ...
    
        }
    
        public void NextModel()
        {
            _index = Mathf.Clamp(_index+1,0,9);
            // code to show your model dress[_index] ...
    
        }