Make a function call itself and return nothing until x = true

Hi!

I am trying to make a function that checks whether a position is within certain bounds and if false, rerolls the position and checks again.
However, I can’t find a way to make the function call itself until that condition is fulfilled.
I also want it to return a Vector3, so I haven’t tried using IEnumerators yet, but if there is a good solution involving IEnumerators, I would of course use that.

Here is my code example:

    Vector3 RepeatCheck(Vector3 position, Vector3 playerPosition)
    {
        if (position.x >= posXLimit.position.x ||
            position.x <= negXLimit.position.x ||
            position.z >= posZLimit.position.z ||
            position.z <= negZLimit.position.z)
        {
            position = SetPosition(position, playerPosition);
            RepeatCheck(position, playerPosition);
        }

        if (Mathf.RoundToInt(position.x) == playerPosition.x &&
            Mathf.RoundToInt(position.z) == playerPosition.z)
        {
            position = SetPosition(position, playerPosition);
            RepeatCheck(position, playerPosition);
        }
        return position;
    }

The lower part is only intended to check whether the object is on top of the player. I try to avoid that because I’ve experienced glitches involving falling through the terrain when that happened, since the object has a collider on it.

Any help is appreciated!

Thank you in advance!

You’re not using the return value of your recursive calls. Changing all your RepeatCheck calls to
return RepeatCheck(position, playerPosition);
Should solve it.

Alternatively, you can just use a loop

Vector3 RepeatCheck(Vector3 position, Vector3 playerPosition)
 {
     while( (position.x >= posXLimit.position.x ||
         position.x <= negXLimit.position.x ||
         position.z >= posZLimit.position.z ||
         position.z <= negZLimit.position.z) && 
        (Mathf.RoundToInt(position.x) == playerPosition.x &&
         Mathf.RoundToInt(position.z) == playerPosition.z))
     {
         position = SetPosition(position, playerPosition);
     }
     return position;
 }