Calculating Scrolling GameObject x position scrolling pass another GameObject x postion (2D Game)

I would appreciate any help that can be provided as the reason this code isn’t working doesn’t make sense to me.

I have a collection/array of obstacles that are moving across the screen (x position) from right to left. I have a player/ship that is located on the left side of the screen.

I would like to kick off a method once one of the obstacles have passed the ship. When I run my code the function kicks off before the object even makes it to the middle of the screen. I don’t understand why this is happening.

My code is as follows:

void Update () 
{
    CheckObstaclePosition();
}


void CheckObstaclePosition() 
{
  Obstacles[] obstaclesIns;
  Obstacles currObstacle; 

  obstaclesIns = FindObjectsOfType();

  if (obstaclesIns.Length > 0) 
     {
        currObstacle = obstaclesIns[0];
        currObstacleVector = currObstacle.transform.position;
        currShipVector = this.gameObject.transform.position;
        
        currObstaclePos = currObstacleVector.x;
        currShipPos = currShipVector.x - 0.2f;
           
        if (currObstaclePos < currShipPos)
           {
                Debug.Log("Obstacle passed Ship");
                AnimateExplosion();  
                currObstacle.DestroyObstacle();
            }

     }  

Can someone explain why this behavior is happening and why the x position of the obstacle is showing that it is passing the ship before it even gets close to the middle of the screen let alone actually getting pass the ship.

First, you’re don’t have any “type” specified in your FindObjectsOfType command. I haven’t seen this before, but I’m guessing it’s just finding all objects in your scene perhaps? And then testing one that you didn’t intend to test against.

So you need a better way of identifying your list of “obstacles”. You could give them all a tag, and use GameObject.FindGameObjectsWithTag, or you could attach them all to a parent object, and enumerate through that object’s childre,

Second, in your code, you’re not checking each obstacle in your list of obstacles - only the 1st (item 0) because of your code which says: obstaclesIns[0]. You haven’t set up a loop to check through each obstacle in the list.

You need to look up “for loops” or "foreach loops"and how to use them.