- Home /
Storing objects in arrays
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.
Answer by Baste · Oct 01, 2014 at 08:42 AM
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.
Answer by Habitablaba · Oct 01, 2014 at 06:47 PM
add the following using:
using System.Linq;
then do the following when trying to find all the objects:
var collection = FindObjectsOftype<YourType>().Where(o => o.YourBoolValue);
Obviously you can use whatever find method you want, and YourType and YourBoolValue should be renamed to be whatever it is you're trying to find.
Your answer
Follow this Question
Related Questions
Array of GameObjects 4 Answers
Collecting Array items in order 1 Answer
Check if boolean is true on my gameObjects from my array 1 Answer
Transport unknown amout of objects with GameObject array 0 Answers
View an array of the transform position/rotation of all game objects with a specified tag., 0 Answers