Find all scripts in a scene and preform an action on it

Hey! I’m making a game, and I have it so that, when a trigger, reaches the player on the z axis, it preforms an action, how I am doing this is that, so when the z position is less than the players, it preforms the action, as well as setting a boolean to false, so afterwards, this action doesn’t constantly repeat. This works fine, until I get into dying. When you die, all it does, is reset the game music, and move the map back to its starting position. But that boolean stays the same, so the trigger won’t be called again when you play.

My idea is to use a script in the obstacle that kills you, so when you die, it finds all of the scripts, named Trigger (What I named the script with the boolean in it), and sets the boolean “triggered” to false.

Here’s what I’ve tried (Didn’t work)

GameObject allGOs = FindObjectsOfType<GameObject>().GetComponent<Trigger>();
allGOs.triggered = false;

Trigger t = FindObjectsOfType<GameObject>().GetComponent<Trigger>();
t.triggered = false;

A couple problems with what you’re trying:

  • FindObjectsOfType returns an array of objects, not a single object. To do something to all of the obejcts in the array you need to use a loop.
  • Why find all GameObjects and then GetComponent on them? Why not just find Triggers directly?

Altogether, should look like this:

Trigger[] allTriggers = FindObjectsOfType<Trigger>();
foreach (Trigger trigger in allTriggers) {
  trigger.triggered = false;
}
1 Like