Hey,
I am not familiar with loops and an array. Unfortunately now I have to deal with both of them
In my scene I have some zones - box colliders as triggers. When my player enters one of these zones, camera behavior changes. Everything worked perfectly untill now. Now I added a new line in an If statement where I want to increase smoothSpeed variable when the player enters the zone. But when he exits it, I am not able to change smoothSpeed value back.
What’s strange, I print string in if and else statement and when the player enters the zone, both of them are prented. Why?
Here’s my code:
if(changeCamBehaviorCubes != null)
{
for (int i = 0; i < changeCamBehaviorCubes.Length; i++)
{
ChangeCameraBehavior changeCameraBehavior_current = changeCamBehaviorCubes*.GetComponent<ChangeCameraBehavior>();*
It’s very vague what you actually want. I guess something like this:
bool outOfAll = true;
for (int i = 0; i < changeCamBehaviorCubes.Length; i++)
{
ChangeCameraBehavior changeCameraBehavior_current = changeCamBehaviorCubes*.GetComponent<ChangeCameraBehavior>();*
if(changeCameraBehavior_current.breakPattern == true) { moveUp = player.transform.position.y; cameraPosition.x = 0; smoothSpeed = 8; outOfAll = false; print(“In a box.”); } } if (outOfAll) { // We’re not inside any box } Additionally, since you get your “changeCamBehaviorCubes” array once at start you might want to directly store your “ChangeCameraBehavior” instances in the array instead of GameObjects. That way you avoid calling GetComponent all the time. // add at the top using System.Linq; private ChangeCameraBehavior[] changeCamBehaviorCubes;
void Awake () { changeCamBehaviorCubes = GameObject.FindGameObjectsWithTag (“ChangeBehavior”).Select(g => g.GetComponent()).ToArray(); } If you don’t want to use Linq you can do it manually in a loop void Awake () { GameObject[] tmp = GameObject.FindGameObjectsWithTag (“ChangeBehavior”); changeCamBehaviorCubes = new ChangeCameraBehavior[tmp.Length]; for(int i = 0; i < tmp.Length; i++) { changeCamBehaviorCubes = tmp*.GetComponent();* } } Using arrays and loops are useful when you want to do the same thing to multiple objects. However since each trigger has already a script attached, wouldn’t it be easier to implement those actions right there? OnTriggerEnter2D / OnTriggerExit2D are events which are only called when something happens. By just setting a flag and then poll through an array seems a bit wasteful.