List<Transform> not initializing

This should be fairly simple, but I am missing it. My List is not initialing to any transforms.

So in my game, I hit a button to look for objects of Number type, and compare their y positions to (currently I am returning 54 objects of type Number). Next I weed out the Number(s) outside of the position ranges I want to check for. Next I foreach through each Number, and compare all of their y positions to each position in the checkPositions array, if my y position matches, I add the transform to collectNumbers.

What’s happening is even though my debug will show number position the same as my checkPosition, the collectNumbers does not add that transform.

Should be something simple, anyone see anything I missed (ignore numLines & ctr parameters, those are used for other logic not posted here)?

Thanks

public List<Transform> collectNumbers = new List<Transform>();
private float[] checkPositions = { -2f, -1f, 0f, 1f, 2f, 3f, 4f }; 

public void RemoveGridRows(int numLines)
{
  Number[] numbers = GameObject.FindObjectsOfType<Number>();
  StartCoroutine(RemoveRow(numLines, numbers));
}
   
private IEnumerator RemoveRow(int ctr, Number[] checkNumbers)
{      
  // for now we get arrays of any Number script in each row
  foreach (Number number in checkNumbers)
  {
    if (number.transform.position.y != 500f 
        && number.transform.position.y != 5.2f 
        && number.transform.position.y != -2.35f)
    {
      for (int i = 0; i < checkPositions.Length; i++)
      {
        Debug.Log(number.name + " position: "+number.transform.position.y + " CheckPosition["+i+"] = "+checkPositions[i]);
      if (number.transform.position.y == checkPositions[i])
      {
          // add the transform
          collectNumbers.Add(number.transform);
      }
    }
  }
}   
       
        yield return new WaitForSeconds(1f);
    }

Do not check for equality with floating point numbers. All Vector3 elements are floating points.

The reason you cannot test for equality is due to floating point accuracy errors. They may print out the same but not be the same.

Instead use a function such as Mathf.Approximately(), which is built in:

Or I prefer to make my own “close enough” function so I know precisely how close is “close enough.”

1 Like

Working perfect now!

Thank you very much Kurt-Dekker!

-Larry

1 Like

Using the Vector3 == operator is another option, and would result in more readable code.