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.