activating game objects with a tag

I have this code

if (turretBaseID==true)
    {
        tb1.active=true;
        tb2.active=true;
        tb3.active=true;
        tb4.active=true;
        tb5.active=true;
        tb6.active=true;
        }

but instead of the the many lines of .active=true, is it possible to have a line writing any gameobject with the tag tb.active=true?

1 Answer

1

Yes. Use a for loop like this:

In C#:

public GameObject[] tbObjects;

for (int i = 0;i<tbObjects.Length;i++) {
    tbObjects*.active = true;*
*}*
*```*
*<p><strong>In JS:</strong></p>*
*```*
*var tbObjects : GameObject[];*
*for(var i = 0;i<tbObjects.length;i++) {*
 _tbObjects*.active = true;*_
_*}*_
_*```*_
_*<p>This is assuming that your `tb` objects are references to GameObjects. If they're not, you can replace the array variable type with whatever object you are using. Populate the array with references to your `tb` objects in the Inspector. If that's not an option, let me know and I'll try to come up with an alternate solution if I have time.</p>*_
_*<p><em>Please note that above script examples are untested and report any errors accordingly.</em></p>*_

You need to set the size to the amount of objects you have (in your case, set 0 to 6), then drag each object into a slot that matches its number-1. Because arrays are zero-based (start counting on 0), you'll want to match up tb1 with position 0, tb2 with position 1, tb3 with position 2, etc.

Replace the tbObjects_.active = true; line with tbObjects*.active = false; and it should work. :)*_

No problem, glad I could help. :)