I want to store objects in arrays, now I know how to do it and all that by tag or by name or what not, but I want it to be stored when they have a boolean set to true, or is there a way from me to store the objects in an array from the object’s its script itself?
What I’m looking for is bsically this
Script → make array with objects in scene but only those that have a boolean set to true
or
Gameobject → something happens → stores itself in an array in another script.
This is pretty simple. I’m assuming C#, but it should be pretty similar in each language. Protip for the future; always, always write down what language you’re using.
Say you have a script MyScript, and MyScript has a boolean variable myBool, and you want to make a list of all gameobjects that has MyScript attached, and myBool set to true. There’s two basic ways to do this; the first one with only arrays is a bit long:
MyScript[] arr = FindObjectsOfType<MyScript>();
int numTrue = 0;
foreach (MyScript t in arr) {
if (t.myBool)
numTrue++;
}
//This is the array you're looking for
GameObject[] withTrue = new GameObject[numTrue];
int idx = 0;
foreach (MyScript t in arr) {
if (t.myBool)
withTrue[idx++] = t.gameObject;
}
The second one, using a List, is much better, but requires you to import System.Collections.Generic (with a using statement):
MyScript[] arr = FindObjectsOfType<MyScript>();
List<GameObject> withTrue = new List<GameObject>();
foreach (MyScript t in arr) {
if (t.myBool)
withTrue.Add(t.gameObject);
}
Lists are in all ways superior to arrays, and you should learn to use them as quickly as possible, as they’ll reduce your headache by tons.