В качестве альтернативы ответа, используя 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);
}
Таким образом, если вы нажмете следующую на последней записи, она перейдет к первой, а не будет ничего не делать.
если я понимаю ваш комментарий
значение индекса у меня такое же, как и у модели, присутствующей в сцене
правильно, вы имеете в виду, что при запуске этого скрипта вам нужно получить текущую зависимость индекса от текущей активной модели:
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);
}