- Home /
Foreach loops only runs once, on one object in an array.
Hey everyone,
This particular issue has had me at wit's end for a while now and I'm hoping someone here can push me into the right direction.
The situation is as follows, I have two objects (simple duplicate cubes) and have one script for both, both are in an array (_player.waterFalls)
When I jump from my Player script, I tell this script to set one of the cubes to isTrigger, and the other to isTrigger is false.
This has consistently worked perfectly for one of the cubes. The other unfortunately has remained entirely inanimate and doesn't even print my Debug.Logs.
It is as if there isn't even a script on there.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Waterfall : MonoBehaviour
{
[SerializeField]
private bool frozen;
[SerializeField]
private BoxCollider2D collider;
private Player _player;
// Start is called before the first frame update
void Start()
{
collider = GetComponent<BoxCollider2D>();
_player = GameObject.Find("Player").GetComponent<Player>();
}
// Update is called once per frame
void Update()
{
foreach (GameObject waterfalls in _player.waterFalls)
{
if (frozen)
{
gameObject.layer = LayerMask.NameToLayer("Ground");
collider.isTrigger = false;
}
else if (!frozen)
{
gameObject.layer = LayerMask.NameToLayer("Default");
collider.isTrigger = true;
}
}
}
public void FreezeUnfreeze()
{
foreach (GameObject waterfalls in _player.waterFalls)
{
if (frozen)
{
frozen = false;
Debug.Log(name);
break;
}
else if (!frozen)
{
frozen = true;
Debug.Log(name);
break;
}
}
}
}
To summarize, the FreezeUnfreeze proc above does exactly what it's supposed to do, but only for the first cube I attached the script to.
And yes, I have them correctly loaded up in the inspector and applied the scripts.
Additionally, this is how I reference and call the script.
waterFall = GameObject.Find("Waterfall").GetComponent<Waterfall>();
waterFall.FreezeUnfreeze();
Thanks for reading.
Answer by n_rusev · Apr 04, 2020 at 04:25 PM
Hello. Your problem might be that GameObject.Find("Waterfall").GetComponent(); returns only one object. You can instead create a tag "Waterfall" and call like so:
foreach(GameObject waterfall in GameObject.FindGameObjectsWithTag("Waterfall"))
{
waterfall.GetComponent<Waterfall>().FreezeUnfreeze();
}
Unfortunately that didn't change anything, thanks for the suggestion though.
Upon further (mild) tinkering, it worked out after all, thank you so much! This stuff was driving me crazy for days!
For future readers;
N_rusev's solution but omitting ''GetComponent()'''from n_rusev's code solved it for me.
Your answer
![](https://koobas.hobune.stream/wayback/20220612230511im_/https://answers.unity.com/themes/thub/images/avi.jpg)