How to wait for each coroutine to finish

Hello,

What I’m trying to do: I set off a trigger, then after a random amount of seconds for each game object, I want their constaints to be removed, so they fall.

What is happening: The constraints are being removed for all game objects at the same time, before their coroutine finishes.

What I tried: I thought of handling the constraint removal within the IEnumerator, but I wasn’t sure how to reference the rigid body outside of the trigger method.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TriggerFall : MonoBehaviour
{
    [SerializeField] private GameObject[] cubes;

    private void OnTriggerEnter(Collider other)
    {
        if (other.tag == "Player")
        {
            foreach (GameObject cube in cubes)
            {
                Rigidbody cubeRb = cube.GetComponent<Rigidbody>();

                StartCoroutine(WaitBeforeFall());

                cubeRb.constraints = RigidbodyConstraints.None;
            }
        }
    }

    private IEnumerator WaitBeforeFall()
    {
        float fallTime = Random.Range(3, 30);

        yield return new WaitForSeconds(fallTime);

        Debug.Log("I fell after a random amount of seconds");
    }
}

Thank you for your time, I’m sure it’s something simple. I couldn’t find an answer.

Great news, I managed to solve it! I’m not sure if this is the most efficient way but I’m very happy it now works -
public class TriggerFall : MonoBehaviour
{
[SerializeField] private GameObject cubes;
[SerializeField] private Rigidbody cubeRb;
[SerializeField] private bool isTriggered = false;

    private void Start()
    {
        cubeRb = new Rigidbody[cubes.Length];
    }

    private void OnTriggerEnter(Collider other)
    {
        if (other.tag == "Player" && isTriggered == false)
        {
            isTriggered = true;

            for (int i = 0; i < cubes.Length; i++)
            {
                GameObject cube = cubes*;*

cubeRb = cube.GetComponent();
}

foreach (Rigidbody rb in cubeRb)
{
StartCoroutine(WaitBeforeFall(rb));
}
}
}

private IEnumerator WaitBeforeFall(Rigidbody rb)
{
float fallTime = Random.Range(0f, 5f);

yield return new WaitForSeconds(fallTime);

rb.constraints = RigidbodyConstraints.None;
Debug.Log(“I fell after a random amount of seconds”);
}
}