Home > front end >  Check for numbers as string in two gameObjects
Check for numbers as string in two gameObjects

Time:06-07

I have a list of GameObjects that have names like

cube 1
cube 2
cube 3

Now I have another list of GameObjects that also have names like

sphere 4
sphere 2
sphere 8

Now I am comparing these two lists, I want the statement to be true if the numbers match. That is, if cube "2" == sphere "2", how do I do this? Also the Count of both lists remain equal.

public List<GameObject> cube = new List<GameObject>();
public List<GameObject> sphere = new List<GameObject>();

void Start(){
  for(int i=0; i<cube.Count; i  ){
   //Check if the string in their names for numbers match
 }
}

CodePudding user response:

void Start(){
    // step 1: store indices of cubes in dictionary
    Dictionary<int, int> cubeIdToIndex = new Dictionary<int, int>();

    for (int cubeIndex = 0; cubeIndex < cube.Count; cubeIndex  ) {
        string name = cube[cubeIndex].name;
        int id = int.Parse(name.Substring(name.LastIndexOf(' ')));
        cubeIdToIndex[id] = cubeIndex;
    }

    // step 2: check spheres
    for (int sphereIndex = 0; sphereIndex < sphere.Count; sphereIndex  ) {
        string name = sphere[sphereIndex].name;
        int id = int.Parse(name.Substring(name.LastIndexOf(' ')));
        if(cubeIdToIndex.TryGetValue(id, out int cubeIndex)) {
            // here cube[cubeIndex] matches sphere[sphereIndex]
        }
    }
}

There are more efficient ways to do this, but IMHO this one is a good tradeoff between performance and understandability.

However you should think about reorganizing your data structure, because matching based on naming convention is inefficient and error prone.

  • Related