- Home /
Activate/deactivate all GameObjects with same tag c#
I'm trying to create a script which would automatically activate and reactivate all GameObjects with the tag 'Flare' on them. 'flareOnTime' is for how long it is active and 'flareOffTime' is for how long it is inactive. I'm stuck right now and cannot figure out what is wrong with my code. I would reaaly appriciate any help.
Code:
using UnityEngine;
using System.Collections;
public class GameController : MonoBehaviour {
public float flareOnTime;
public float flareOffTime;
GameObject[] gos;
// Use this for initialization
void Start () {
GameObject[] gos = GameObject.FindGameObjectsWithTag("Flare");
StartCoroutine("BlinkFlare");
}
// Update is called once per frame
void Update () {
}
IEnumerator BlinkFlare() {
while (true) {
yield return new WaitForSeconds (flareOnTime);
foreach (GameObject go in gos){
go.SetActive(false);
}
yield return new WaitForSeconds (flareOffTime);
foreach (GameObject go in gos){
go.SetActive(true);
}
}
}
}
In what way does this not behave as expected? Please include that information when asking questions, thanks. :)
$$anonymous$$aybe it's not an error, but there's no good reason you should start the coroutine with a string when you already know the name and are in the same scope.
StartCoroutine(BlinkFlare());
Throw in some Debug.Logs to see if you can narrow down the culprit.
Sorry for not being specific enough, I try to do it better now(I'm very new to coding:) ). The problem with this script is the gameobjects with Flare tag are not blinking. I get the following error in console:
'NullReferenceException: Object reference not set to an instance of an object GameController+c__Iterator0.$$anonymous$$oveNext () (at Assets/Scripts/GameController.cs:41)'
GameController.cs is the script file where this script is.
I managed to make this script working previously but only for 1 GameObject. The difference was the I had a public GameObject named flare and the part of the code which is now
'foreach (GameObject go in gos){
go.SetActive(false/true);'
was simply
'flare.SetActive(false/true);'
and like this it was working perfectly but only for the one object.
Answer by Baste · Mar 12, 2015 at 11:59 AM
The error is that you're re-initalizing the array of GameObjects by doing this:
GameObject[] gos = GameObject.FindGameObjectsWithTag("Flare");
instead of this:
gos = GameObject.FindGameObjectsWithTag("Flare");
Essentially, when you write "MyClass foo = ", you're introducing a new variable named "foo" in the local scope, hiding any variable named foo in outer scopes - like class variables. So, in your start method, you're making a new array, and filling it with all of the objects tagged with "Flare", but you're not doing anything with it. The BlinkFlare method uses the empty game object field variable, and thus does nothing.