0
\$\begingroup\$

How to deactivate current object in array and activate next one by using button click?

public GameObject[] gameObjects;
private int numOfgameObjects;

void Start()
{

  //current object
  gameObjects[0].SetActive(true);

  int numOfgameObjects = gameObjects.Length;

  for (int i = 0; i < numOfgameObjects ; i++)
  {
      gameObjects[i].SetActive(false);
  }

}

public void NextPrefab_ButtonClick()
{
  // Some Code to deactivate current object and activate next one
}
\$\endgroup\$
1
\$\begingroup\$

This is pretty trivial: just track the index of the current selection in a variable, and increment that variable when you want to select the next item. You may want to work your way through some beginner C# tutorials if this use of variables is unfamiliar.

public GameObject[] gameObjects;

// Track which object we've currently selected.    
int _selectedObjectIndex = -1;

public void SelectObject(int selectedIndex)
{
    // Disable the previous selected object, if any.
    if(_selectedObjectIndex >= 0)
        gameObjects[_selectedObjectIndex].SetActive(false);

    // Update our selected index and activate the corresponding object.
    _selectedObjectIndex = selectedIndex;
    gameObjects[selectedIndex].SetActive(true);
}

void Start()
{
    for (int i = 0; i < gameObjects.Length; i++)
    {
        gameObjects[i].SetActive(false);
    }

    SelectObject(0);
}

public void NextPrefab_ButtonClick()
{
    // Compute the next index in the list.
    // The modulo operator % "wraps" our index around to zero when we pass the last object.
    int nextObjectIndex = (_selectedObjectIndex + 1) % gameObjects.Length;
    SelectObject(nextObjectIndex);
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.