如何比较列表对象的顺序

时间:2014-05-22 10:57:04

标签: unity3d unityscript

我有两个名为gems和gems1的列表,其中我有16个对象的克隆,并且它们在列表中以唯一的名称存储。之后一个列表被洗牌。现在我想比较列表的顺序是否相同。我该怎么做.. ??

 for(int a=GridHeight;a>0;a--){
                for(int b=0;b<GridWidth;b++)
            {
                     g =  Instantiate(gemprefab, new Vector3 ( b,a, 0), Quaternion.identity) as GameObject;

                    g.name= "gem"+ t;
                    g.transform.parent = gameObject.transform;

                    LastGem=g.GetComponent<Gem>();
                    gems1.Add(LastGem);

                    gemComponent = g.GetComponent<Gem>();
                    gems.Add(gemComponent);
    t++;
    }
for(int i = 0; i < gems.Count; i++) {
            Vector3 temp = gems[i].transform.position;
                 randomIndex = Random.Range(0, gems.Count);
            gems[i].transform.position = gems[randomIndex].transform.position;
            gems[randomIndex].transform.position = temp;
            //print (gems[i]);
            //print (gems1[i]);
        }
        }
        void comp() 

        {
              for (int i = 0; i < gems.Count; i++) {
                     for (int j = 0; j< gems1.Count; j++) {

                     if(gems[i].transform.name.StartsWith(gems1[j].transform.name))
                     {
                      break;
                          //print ("gems[i].transform.name");
                          //print ("gems1[i].transform.name");

                     }

        }

1 个答案:

答案 0 :(得分:0)

你很近,但你使用的循环太多了。你想要的是直接比较每个对象,因为它们具有相同的长度,你可以在一个循环中完成。

UnityScript

import System.Collections.Generic;

...

function listsEqual(a : List.<GameObject>, b : List.<GameObject>)//I am assuming that GameObject is the type, but it could be different
{
    for (var i = 0; i < a.Count; i++)
    {
        if (a[i] != b[i])
        {
            return false;
        }
    }
    return true;
}

C#

bool ListsEqual(List<GameObject> a, List<GameObject> b)//I am assuming that GameObject is the type, but it could be different
{
    for (var i = 0; i < a.Count; i++)
    {
        if (a[i] != b[i])
        {
            return false;
        }
    }
    return true;
}

然后你可以简单地实现它:

if (listsEqual(gems, gems1))
{
    //code goes here
}