- Home /
Find GameObjects with a true boolean and put them in an array?
I'm trying to place a bunch of similar gameobjects into an array that have the same true value as to be 'active'.
Here is my code, which I understand why it is wrong, I'm trying to get a bool and put it into a gameobject array, not going to work, can't figure out how to do this without doing a Gameobject.FindObjects with Tag, and make the other script put the box in the active tag whenever I do something, however that just seems cumbersome, any better ways?
public GameObject[] activeBoxArray;
public GameObject[] boxArray; // This is set to 7, and is the amount of boxes I normally have, when I click on them, the boxActive bool is set to true, and then I want to put that in the new array when the game is started by the player.
if (Input.GetKey(KeyCode.Return))
{
for (int i = 0; i < boxArray.Length; i++)
{
activeBoxArray[i] = GameObject.Find("Box" + i.ToString()).GetComponent<BoxController>().boxActive == true;
}
}
Answer by MakinStuffLookGood · Dec 16, 2014 at 04:14 PM
using System.Linq;
..
..
activeBoxArray = FindObjectsOfType<BoxController>().Where(b => b.boxActive).Select(b => b.gameObject).ToArray();
A little bit of Linq and lambdas can do this in one line without any looping, string concatenation, or GetCompontent. This finds all the BoxControllers where boxActive is true, then we select the actual gameObjects rather than the BoxController component, and finally do a ToArray on our resultant set.
If you decide that:
public GameObject[] activeBoxArray;
could actually just be:
public BoxController[] activeBoxArray;
then you can remove the select query.
Despite being right, this answer is not recommended for iOS. This is due to the Linq not being well welcome by Xcode (at least it used to be). So you may have to decompose to something more old school.
BoxController[] objs = FindObjectsOfType<BoxController>();
List<GameObject> activeBox = new List<GameObject>();
foreach(BoxController bc in objs)
{
if(bc.boxActive)
{
activeBox.Add(bc.gameObject);
}
}
Right, I assumed from the use of "Input.Get$$anonymous$$ey($$anonymous$$eyCode.Return)" that this was not being developed for mobiles. In the case of mobiles, you'd really want to avoid the FindObjects and foreach entirely, they can cause GC issues depending on how frequently this thing is being called. And we all know how gross GC lag spikes can be on iOS.
Thanks for the help guys, just wondering is this reusable? The game is blackjack and I want it to be reusable when the game ends, would I just clear the list when the game finishes?
Your answer
Follow this Question
Related Questions
Using getcomponent with an array 2 Answers
error CS0118: `New_Career.Fame' is a `field' but a `type' was expected 1 Answer
Alter a GameObjects(Clone) array from another script C# 0 Answers
GetComponent with arrays C#? 0 Answers
2D array of GameObjects C# 2 Answers