[SOLVED] Check if a list of Vector3 contains a x-value

Hey guys!

I’ve been trying to figure this out by myself for a couple of hours now, and Googling didn’t help. Anyways, I have two lists of Vector3:s called VectorList1 and VectorList2. Now I want check for every Vector3 in the first list: does the second list have a vector with that x-value?. Anyone have any idea how this can be done?

This doesn’t work, but I put it there if it’s easier to see in code what I want to achieve, than my explanation:

private List<Vector3> VectorList1 = new List<Vector3>();
private List<Vector3> VectorList2 = new List<Vector3>();

// [Code where vectors has been added to to both lists]

for (int a = 0; a < VectorList1.Count(); a++){
if (VectorList2.Contains(VectorList1[a].x)){
Debug.Log("VectorList2 has a vector with that x-value");
}
}

You should not check for exact matches, because of Float Precision

for( int i = 0; i < List1.Count; i++ ){
  for( int j = 0; j < List2.Count; j++ ){
    if(Mathf.Approximately(List1[i].x, List2[j].x)){
      //Something
    }
  }
}
2 Likes

Didn’t know about approximately. Just checked the docs, couldn’t find the margin. Any ideas on what it is?

1 Like

Pretty small, apparently. I ran this just to get an approximation (pun) of what it was:

using UnityEngine;
using System.Collections;

public class ApproxTest : MonoBehaviour {

    [SerializeField]
    float initialValue = 0.1f;

    void Start()
    {
        ApproxTestGo();
    }

    void ApproxTestGo()
    {
        float baseValue = 1.0f;
        float tolerance = initialValue;

        int i = 0;
        int maxIterations = 100;

        while (true)
        {
            if (Mathf.Approximately(baseValue, baseValue + tolerance))
                break;

            tolerance = tolerance * 0.5f;

            i++;

            if (i > maxIterations)
            {
                Debug.Log("max!");
                break;
            }
        }

        Debug.Log(i);
        Debug.Log(tolerance);
    }
}

EDIT: Forgot to mention! It goes to 6 decimal places, so when you get 1.0 and 1.000001 it reads them as equal.

Of course, if you want a specific threshold this is easy enough to code on your own.

1 Like

The margin is probably Mathf.epsilon

Oh, okay. Never heard of Approximately either. But it works, so thank you! :slight_smile: