- Home /
How to store gameobjects in an array
Hello,
I have a scene where there are 10 game objects with some properties. How can I store them on an array and check if a specific property is true for each one of them??
Thanks!
Answer by Nick4 · Mar 02, 2014 at 11:51 AM
What kind of properties? If things like isTrigger variable in Collider component is what you mean then you should write a code where only gameObjects with isTrigger enabled will be added to your array. But I'd suggest lists in this case. So, something like this would do it.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class myClass : MonoBehaviour
{
List<GameObject> objects = new List<GameObject>();
Vector3 center = new Vector3(/* Wherever you want to start sphere casting*/)
float radius;
void Update()
{
foreach(Collider co in Physics.OverlapSphere(center, r))
{
if(co.gameObject.GetComponent<Collider>().isTrigger == true)
{
objects.Add(co.gameObject);
}
}
}
}
It's not a trigger, it's a variable on a Js each one has (var selected : boolean)
If it's a custom variable, define its access modifier public then do the same except this time you'll need to change the name of your component and variable.
Example :
if(co.gameObject.GetComponent<$$anonymous$$yScript>().myVariable == true)
{
objects.Add(co.gameObject);
}
I'm not very familiar with javascript but I think this should do it :
var objects : List.<GameObject> = new List.<GameObject>();
var center : Vector3;
var radius : float;
function Update()
{
for (var co : Collider in Physics.OverlapSphere(center, r))
{
if(co.gameObject.GetComponent<Collider>().isTrigger == true)
{
objects.Add(co.gameObject);
}
}
}
Good luck.
Answer by mclankyman · Mar 02, 2014 at 11:10 AM
public GameObject[] gameObjects;
void Update()
{
for(int i = 0; i < gameObjects.Length; i++)
{
//could test what you wanted here
if(gameObjects[i].activeSelf)
{
//do something
}
}
}
You would need to assign the GameObjects in the inspector if they were public like this. You can always assign the GameObjects in code if you wanted to.
I can't assign them on the inspector. They are generated on run time. Is there a way I can do that with code?
Your answer
![](https://koobas.hobune.stream/wayback/20220613135149im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
how do i make a loop for a boolean? 2 Answers
Getting length of array based on a loop search? 1 Answer
Material doesn't have a color property '_Color' 4 Answers
What am I overlooking? -1 Answers
Create a Searcher To find [n] Text's (results) of Array[n] 0 Answers