- Home /
How do I for each active all objects by tag?
I have 100 objects with this same tag and I need to activate all, but with delay ~~3-4s each. How to do this? :)
Answer by YoungDeveloper · Jul 28, 2015 at 05:05 AM
private void Start(){
StartCoroutine(Run());
}
private IEnumerator Run(){
GameObject[] gameObjects = GameObject.FindGameObjectsWithTag("yourTag");
float waitTime = 3f;
foreach (GameObject go in gameObjects) {
yield return new WaitForSeconds(waitTime);
go.SetActive(true);
}
}
If you want random time
float waitTime_from = 3f;
float waitTime_to = 4f;
yield return new WaitForSeconds(Random.Range(waitTime_from, waitTime_to));
Answer by NeverHopeless · Jul 28, 2015 at 07:28 AM
I see two problems here then, as per the documentation of GameObject
for finding game objects, it seems we can't get the in-active game objects using these functions. The other way around is to reference the game object using public
modifier and use it in the script to deal with it, but it is an overkill for your case since you have 100 game objects.
I would advice:
To set these game objects as ACTIVE in the beginning.
Add them to collection
List<GameObject>
and InActivate them.Later loop over the collection and activate them as per your need.
For activating them, you can use Coroutine
with WaitForSeconds
as already suggested. There is another option to use Invoke
function.
A possible workout:
Your main script:
void Start () {
float delay = Random.Range (3, 4);
foreach (GameObject go in gameObjects) {
delay = delay + Random.Range (3, 4);
go.SendMessage("ActivateAfterDelay", delay, SendMessageOptions.DontRequireReceiver);
}
}
Tagged object's behaviour script:
void ActivateAfterDelay(float delay) {
Invoke ("EnableObject", delay);
}
void EnableObject() {
gameObject.SetActive(true);
}
Hope it helps!