Hi,
I have a test class setup like this:
public class BoundsTest : MonoBehaviour
{
[SerializeField] private BoxCollider2D boxCollider;
public Bounds Bounds => boxCollider.bounds;
}
Another class is instantiating a prefab of the above. After instantiation I want to move the object, and get the updated Bounds. I realize that it may take some time for the box collider to update thus I’m waiting for a frame to get its values.
public class BoundsChecker : MonoBehaviour
{
[...]
//I'm running this as StartCoroutine(TestWithWait());
private IEnumerator TestWithWait()
{
instance = Instantiate(prefab);
Debug.Log("Bounds center before: " + instance.Bounds.center); //Logs (0,0,0)
instance.transform.position += new Vector3(2, 0);
Debug.Log("Bounds center after: " + instance.Bounds.center); //Logs (0,0,0)
yield return null;
Debug.Log("Bounds center after wait: " + instance.Bounds.center); //Logs (0,0,0), sometimes (2,0,0)
}
}
The problem I’m facing is getting the bounds center is not consistent at all. The logged center right after the position change is the same as before moving as I expected. The problem is even though I wait for the end of the frame the bounds are sometimes still not updated. 9 times out of 10 it logs out the default value. Sometimes I get lucky and logs out the correct center.
Waiting for some seconds does the trick. By that time the bounds are updated but I obviously don’t want to wait for that long.
Is there a way to get consistent results without having to wait too long and clutter my code with hardcoded wait values?
Thanks in advance