- Home /
How can I animate between 3 gameObjects?
I have 3 gameObjects, all the with the same tag, and each have many children. The first one starts out as visible in the game, while the second and third are initially hidden/de-activated (by un-checking the box in the inspector).
When it gets collided into, I need it to hide, show the second gameObject in its place, then hide the second gameObject, and show the third gameObject, then hide the third gameObject, show the second gameObject, then hide the second gameObject, and show the first gameObject again.
The problem I'm running into is I'm trying to do this in a coroutine and grabbing the 3 gameObjects like so: GameObject[] myObjects = GameObject.FindGameObjectsWithTag("myTag");
But it's only finding the one that's not hidden.
Any ideas on how to animate between these 3 objects?
Thanks!
Answer by Scribe · May 06, 2013 at 04:35 PM
You are correct that .Find() will not work on inactive GameObjects so the easiest way to work round this is to saved the objects at the start into a list and then deactivate them afterwards by code.
So make sure you have all the objects activated to start with and then use:
GameObject[] myObjects = GameObject.FindGameObjectsWithTag("myTag");
in a 'Start' function
Here is some C# code as it looks like that is what you are using, however I will disclaim that I am very bad at C# and tend to write in unityscript when using Unity (I have therefore also included the unityscript code below incase there are errors in the C# code)
C# version
using UnityEngine;
using System.Collections;
public class find : MonoBehaviour {
GameObject[] myObjects;
void Start () {
myObjects = GameObject.FindGameObjectsWithTag("myTag");
for(var a = 0; a < myObjects.Length; a++){
myObjects[a].active = false;
}
myObjects[0].active = true;
}
void OnTriggerEnter (Collider other) {
for(var i = 0; i < myObjects.Length; i++){
if(other.gameObject == myObjects[i]){
myObjects[i].active = false;
myObjects[((i+1)%myObjects.Length)].active = true;
}
}
}
}
Unityscript version
var myObjects : GameObject[];
function Start () {
myObjects = GameObject.FindGameObjectsWithTag("myTag");
for(var obj in myObjects){
obj.active = false;
}
myObjects[0].active = true;
}
function OnTriggerEnter (other : Collider) {
for(var i = 0; i < myObjects.Length; i++){
if(other.gameObject == myObjects[i]){
myObjects[i].active = false;
myObjects[((i+1)%myObjects.Length)].active = true;
}
}
}
I hope that works for you, remember to have all 3 objects active when the scene starts else it will not find the objects as you have found out.
Scribe