- Home /
How to trigger different prefabs (JavaScript)
Ok, so I have a prefab, lets say it's called platform. Now I've made 2 objects on the screen using that prefab, and called them, platform1 and platform2.
My hierarchy looks like this
- Field (Empty Object with script explosion as Component)
- platform1 (gameObject)
- explosion (script Detonator as Component)
- platform2 (gameObject)
- explosion (script Detonator as Component)
- platform1 (gameObject)
Now I want to trigger both explosions at the same time and I've tried the following JS script:
var explosion : Detonator; var ready : boolean = true;
function Update () { if(ready) { Explode(2); } }
function Explode(t : int) { ready = false; explosion1 = gameObject.Find("platform1").Find("explosion").GetComponent(Detonator); explosion = gameObject.Find("platform2").Find("explosion").GetComponent(Detonator); explosion1.Explode(); explosion.Explode(); yield WaitForSeconds(t);
ready = true;
}
but for some reason, only the second platform gets triggered. Does anyone know how to fix this? Thanks in Advance, Dave
Answer by Cyb3rManiak · May 08, 2011 at 02:30 PM
If I remember correctly, gameObject.Find() is not relative... It searches the entire scene, and you're probably getting the 2nd explosions both times. transform.Find() however, is.
try
var tField: Transform = GameObject.Find("Field").transform;
explosion1 = tField.Find("platform1/explosion").GetComponent(Detonator); explosion2 = tField.Find("platform2/explosion").GetComponent(Detonator);
or...
explosion1 = GameObject.Find("Field/platform1/explosion").GetComponent(Detonator);
explosion2 = GameObject.Find("Field/platform2/explosion").GetComponent(Detonator);
Alternatively you could:
var tField: Transform = GameObject.Find("Field").transform;
foreach (var currDetonator: Detonator in tField.GetComponentsInChildren(typeof(Detonator))) { currDetonator.Explode(); }
Answer by GesterX · May 08, 2011 at 02:20 PM
You haven't declared explosion1 as a variable at the top of your script. You need this:
var explosion : Detonator;
var explosion1 : Detonator;
var ready : boolean = true;