- Home /
How to cut off an array of gameobjects?
Hello, I created a script which changes behavior of a camera in 2D. The behavior is changed by other script attached to triggers in the scene simply by setting bool. Then in my camera script I want to find all the triggers with tag and deside if the bool in other script is true then do something. Everything works fine, but only with the first find component. Always changes behavior the first trigger but not the others. I thing the problem is in my script bellow when working with an array. Any help please?
private ChangeCameraBehavior changeCameraBehavior;
void Awake ()
{
GameObject[] changeCamBehaviorCubes = GameObject.FindGameObjectsWithTag ("ChangeBehavior");
for (int i = 0; i < changeCamBehaviorCubes.Length; i++) {
changeCameraBehavior = changeCamBehaviorCubes[i].GetComponent<ChangeCameraBehavior>();
}
}
void Update ()
{
if(changeCameraBehavior.breakPattern == true)
{
//do something
}
Answer by Cherno · Aug 01, 2015 at 11:14 AM
Inside your loop, you assign the current ChangeCameraBehavior component to the changeCameraBehavior variable. This means that if the loop runs once in Awake(), this variable will get overwritten during the loop until only the last component is the one that is stored by it. Then, when Update() is called, the variable is accessed, but since it only holds the last component that was assigned to it, only that component will be affected.
You could just "do something" directly in the loop:
void Awake ()
{
GameObject[] changeCamBehaviorCubes = GameObject.FindGameObjectsWithTag ("ChangeBehavior");
for (int i = 0; i < changeCamBehaviorCubes.Length; i++) {
ChangeCameraBehavior changeCameraBehavior_current = changeCamBehaviorCubes[i].GetComponent<ChangeCameraBehavior>();
if(changeCameraBehavior_current .breakPattern == true)
{
//do something
}
}
}
Or, if you need to hold references to all the tagged GameObjects, declare the changeCamBehaviorCubes array in the script's main body so it can be accessed by all functions.
private GameObject[] changeCamBehaviorCubes;
void Awake ()
{
changeCamBehaviorCubes = GameObject.FindGameObjectsWithTag ("ChangeBehavior");
}
void Update ()
{
if(changeCamBehaviorCubes != null)
{
for (int i = 0; i < changeCamBehaviorCubes.Length; i++) {
ChangeCameraBehavior changeCameraBehavior_current = changeCamBehaviorCubes[i].GetComponent<ChangeCameraBehavior>();
if(changeCameraBehavior_current .breakPattern == true)
{
//do something
}
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220611234003im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to remove gaps in a 2D map. 0 Answers
Array of Tilemaps misbehaving 1 Answer
Getting a 2d Sprite to move over time to an Array 1 Answer
Best way to concat builtin arrays? 2 Answers
Find if no objects with tag exist 3 Answers