- Home /
Help Activating/Deactivating all Game Objects with same tag
The title sums it up. I'm stuck... giving me the error message when colliding with the enemy:
MissingFieldException: Field 'UnityEngine.GameObject[].active' not found.
If I change the code to findwithtag for one enemy then the code works fine. but obviously i have several enemies in my game so I need to figure out how to apply this using an array or something... I know it's probably a simple fix but I'm not seeing it. Any help is appreciated. Here is my code:
private var playerColor : GameObject;
var colors = new Color[2];
var player : GameObject;
function Awake() {
player = gameObject.FindWithTag("Player");
player.animation["RedHit"].wrapMode = WrapMode.Once;
playerColor = gameObject.FindWithTag("ColorFlash");
}
function OnControllerColliderHit(hit:ControllerColliderHit) {
if (!enabled)
return;
var enemyTriggers = GameObject.FindGameObjectsWithTag("EnemyDeathTrigger");
var controllerScript: RedController = GetComponent(RedController);
if (hit.gameObject.tag == "Enemy") {
controllerScript.GetHit();
Time.timeScale = 0.00001;
Physics.IgnoreCollision(gameObject.collider, hit.gameObject.collider);
playerColor.renderer.material.color = colors[0];
player.animation.Stop();
player.animation.Play("RedHit");
player.animation["RedHit"].speed = 1.0/Time.timeScale;
enemyTriggers.active = false; // THIS IS WHERE MY ERROR COMES FROM
yield WaitForSeconds(1 * Time.timeScale);
Time.timeScale = 1.0;
yield WaitForSeconds(1);
playerColor.renderer.material.color = colors[1];
enemyTriggers.active = true;
Physics.IgnoreCollision(gameObject.collider, hit.gameObject.collider, false);
}
You need to treat the enemyTrigger as an array and loop through it, try using this code
for (var go : GameObject in enemyTriggers){ go.active = false; }
Answer by aldonaletto · May 05, 2012 at 07:24 PM
enemyTriggers is a GameObject array: you must deactivate its elements one by one in a loop - like this:
for (var trigger:GameObject in enemyTriggers){
trigger.active = false;
}
Do the same to reactivate them:
for (trigger in enemyTriggers){
trigger.active = true;
}
NOTE: Variables declared inside loops or brackets aren't local to them in JS - that's why trigger must not be re-declared in the second for (it's valid anywhere inside the function)
I've made a mistake: the variable trigger must not be redeclared in the second loop (it's valid inside the whole function). I edited my answer to fix this.