I’m using objectpool to instantiate all my prefabs at the start of the game, how do I activate them randomly every 10 seconds?
Example: I have 5 Colors, every 10 seconds 1 Color Shows Up and the last one goes away.
The five colors are instantiated but deactivated. I want to activate them Randomly.
Without a look at the script I’m not sure how much this will help but I’ll have a go. If your pool is an array/list of GameObjects you could use Random.Range() to find a random element: objectPool[Random.Range(0, objectPool.Length)]
. If you only want one active object at a time you could then store a reference/index for the current active object so that you can deactivate the current and activate a new GameObject:
public GameObject[] objectPool;
private int currentIndex = 0;
public void NewRandomObject()
{
int newIndex = Random.Range(0, objectPool.Length);
// Deactivate old gameobject
objectPool[currentIndex].SetActive(false);
// Activate new gameobject
currentIndex = newIndex;
objectPool[currentIndex].SetActive(true);
}
Now to make this happen every 10 seconds you could monitor time yourself in an update, use a Coroutine or you can use Monobehaviour’s InvokeRepeating. Here’s a super quick example of a timer in update:
float elapsedTime = 0f; // Counts up to repeatTime
float repeatTime = 10f; // Time taken to repeat in seconds
private void Update()
{
elapsedTime += Time.deltaTime;
if (elapsedTime >= repeatTime)
{
// Do something here
...
// Subtract repeat time
elapsedTime -= repeatTime;
}
}
I hope some of that was useful. =)