Hide or show objects in a list not working correctly
Hello ! I wrote a simple script in order to show objects in a list of 16 objects one by one when clicking a button (calling the EnableGameObjects function) and hide them one by one in the reverse order when clicking another button (calling the DisableGameObjects function). The script works, but for example when I want to disable the object I just enabled I need to press the disable button twice (the first click makes the counter count down but the object is getting disabled only on the second click). Here is the script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DisableOrEnableObject : MonoBehaviour
{
public List<GameObject> MyGameObjects = new List<GameObject>(); //Creating the list of objects
public int counter;
void Start()
{
counter = 0;
}
public void EnableGameObjects()
{
MyGameObjects[counter].SetActive(true);
counter++;
if (counter > 15)
counter = 15;
}
public void DisableGameObjects()
{
MyGameObjects[counter].SetActive(false);
counter--;
if (counter < 0)
counter = 0;
}
}
Anyone has any ideea on how can I disable the object I just enabled on the first button click ?
Answer by Hellium · Jun 17, 2021 at 01:45 PM
using System.Collections.Generic;
using UnityEngine;
public class DisableOrEnableObject : MonoBehaviour
{
public List<GameObject> MyGameObjects = new List<GameObject>(); //Creating the list of objects
private int lastActiveObjectIndex;
void Start()
{
lastActiveObjectIndex = -1;
}
public void EnableGameObjects()
{
lastActiveObjectIndex++;
if(lastActiveObjectIndex >= MyGameObjects.Count)
lastActiveObjectIndex = MyGameObjects.Count - 1;
MyGameObjects[lastActiveObjectIndex].SetActive(true);
}
public void DisableGameObjects()
{
if(lastActiveObjectIndex >= 0)
MyGameObjects[lastActiveObjectIndex].SetActive(false);
lastActiveObjectIndex--;
if(lastActiveObjectIndex < -1)
lastActiveObjectIndex = -1;
}
}
Thank you for your help !
if(lastActiveObjectIndex < 0)
lastActiveObjectIndex = 0;
This condition won't allow me to re-enable the first object, but after comparing the index with -1 it works like a charm !