how to not randomly active again object that was deactive in array
Hi there Guys, I have a problem with script to randomly activate object in Array,. But I want that object was Active and then deactive, will not randomly active again, so the object in array will not active twice or active again, please help. this my script, ,
Using UnityEngine;
using System.Collections;
public class button : MonoBehaviour {
public static button Instance;
public GameObject[] objectPool;
private int currentIndex = 0;
void Awake () {
Instance = this;
}
public void random(){
{
int newIndex = Random.Range(1, objectPool.Length);
// Deactivate old gameobject
objectPool[currentIndex].SetActive(false);
// Activate new gameobject
currentIndex = newIndex;
objectPool[currentIndex].SetActive(true);
}
}
I would try something like this. I haven’t tested the code, so I can not guarantee anything :
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class button : MonoBehaviour {
public static button Instance;
public GameObject[] objectPool;
private int currentIndex = 0;
private List<int> availableIndices;
void Awake ()
{
Instance = this;
availableIndices = new List<int>();
for( int i = 0 ; i < objectPool.Count ; ++i )
availableIndices.Add( i ) ;
availableIndices.Remove( currentIndex ) ;
}
public void random(){
{
int newIndex = Random.Range(0, availableIndices.Count );
// Add current index as available for next call to random() function
availableIndices.Add( currentIndex ) ;
// Deactivate old gameobject
objectPool[currentIndex].SetActive(false);
// Activate new gameobject
currentIndex = newIndex;
objectPool[currentIndex].SetActive(true);
// Remove the new index from available indices for next call to random() function
availableIndices.Remove( currentIndex ) ;
}
}
@irfanys, I would suggest your to use Linq and use List instead of array.
Here is how you code should look:
using UnityEngine;
using System.Collections.Generic;
using System.Linq;
public class button : MonoBehaviour
{
public static button Instance;
public List<GameObject> objectPool;
private int currentIndex = 0;
void Awake()
{
Instance = this;
}
public void random()
{
int oldindex = objectPool.IndexOf(objectPool.Where(obj => obj.activeSelf).ToList()[0]);
objectPool[oldindex].SetActive(false);
int newIndex = -1;
while (newIndex<0||newIndex == oldindex)
newIndex = Random.Range(0, objectPool.Count);
objectPool[newIndex].SetActive(true);
}
}