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);
}
}
}
,
You want to only have one object active at any time? Then you want to setActive a new random object that is not already active? If that is what you want this could be a way of doing it.
using UnityEngine;
public class button : MonoBehaviour
{
public static button Instance;
public GameObject[] objectPool;
int index;
void Awake()
{
Instance = this;
if (objectPool.Length == 0)
{
Debug.LogErrorFormat("the objectPool array on \"{0}\" is empthy", this);
}
PoolSetActive(false);
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
FindOneInactiveObjectAndSetActive();
}
}
void FindOneInactiveObjectAndSetActive()
{
FindAndSetRandomInactiveIndex();
PoolSetActive(index);
}
void FindAndSetRandomInactiveIndex()
{
do
{
SetRandomPoolIndex();
} while (objectPool[index].activeSelf);
}
void SetRandomPoolIndex()
{
index = Random.Range(0, objectPool.Length);
}
void PoolSetActive(bool isActive)
{
for (int i = 0; i < objectPool.Length; i++)
{
if (objectPool*.activeSelf != isActive)*
objectPool*.SetActive(isActive);*
}
}
void PoolSetActive(int index)
{
PoolSetActive(false);
objectPool[index].SetActive(true);
}
}
Note that Class and Method names are normaly written with Pascal case.