Setting an Object's Position at a Delayed Time

Hello, thanks for taking the time to help.

My game has a player going through a tunnel. What I’m trying to do is know when the player is outside of the tunnel. If you look at the attached images it will help you understand my problem.

I’m generating mesh procedurally at a distance from the player. The mesh moves towards the player at a changing speed. I’ve created a Sphere Collider on an Empty Game Object at the Z position of the player and I’m looking to have it follow the tunnel’s X and Y coordinates.

I was going to set the Empty’s X and Y coordinates to the Mesh spawn X and Y at a delayed time but that wouldn’t work because the speed the mesh moves at changes constantly. I just need to test if the player is outside of the generated mesh at the player’s position. This doesn’t seem like it should be that difficult but for the life of me I can’t figure it out.


The first image shows my set up, the second shows what I’m trying to accomplish.

I got a little big closer to what I’m trying to accomplish. On my object that spawns the mesh I added the following code to the update function:

StartCoroutine(MoveCollision());

And outside the update function I added the following:

IEnumerator MoveCollision() {
    yield return new WaitForSeconds(2f);
    collider.transform.position = new Vector3(instX, instY, 250);
}

instX is the mesh’s Y spawn and instY is the mesh’s Y spawn. This script has the collider follow the tunnels spawn coordinates on a delay at the players position. The problem is the collider keeps falling in and out of where it has to be because of the varying Z speed on the spawned mesh. I could try to change the WaitForSeconds time based on the speed of the tunnel but I have no idea how I would calculate that equation. Any help is greatly appreciated!!

I have another theory on how I could do this. I’m thinking I can test the position between the player object and the closest mesh object and I would know if it’s outside based on the distance. The problem is the closest mesh is always changing. This still seems like like the most viable option though.

I figured it out using the FindNearestEnemy script from Unity!! Feel free to post if you have any questions related to my issue.