【发布时间】:2017-07-25 16:48:43
【问题描述】:
我正在使用此脚本对数组字母数字进行排序:
public class AlphanumComparatorFast : IComparer<string>
{
public int Compare(string x, string y)
{
string s1 = x as string;
if (s1 == null)
{
return 0;
}
string s2 = y as string;
if (s2 == null)
{
return 0;
}
int len1 = s1.Length;
int len2 = s2.Length;
int marker1 = 0;
int marker2 = 0;
// Walk through two the strings with two markers.
while (marker1 < len1 && marker2 < len2)
{
char ch1 = s1[marker1];
char ch2 = s2[marker2];
// Some buffers we can build up characters in for each chunk.
char[] space1 = new char[len1];
int loc1 = 0;
char[] space2 = new char[len2];
int loc2 = 0;
// Walk through all following characters that are digits or
// characters in BOTH strings starting at the appropriate marker.
// Collect char arrays.
do
{
space1[loc1++] = ch1;
marker1++;
if (marker1 < len1)
{
ch1 = s1[marker1];
}
else
{
break;
}
} while (char.IsDigit(ch1) == char.IsDigit(space1[0]));
do
{
space2[loc2++] = ch2;
marker2++;
if (marker2 < len2)
{
ch2 = s2[marker2];
}
else
{
break;
}
} while (char.IsDigit(ch2) == char.IsDigit(space2[0]));
// If we have collected numbers, compare them numerically.
// Otherwise, if we have strings, compare them alphabetically.
string str1 = new string(space1);
string str2 = new string(space2);
int result;
if (char.IsDigit(space1[0]) && char.IsDigit(space2[0]))
{
int thisNumericChunk = int.Parse(str1);
int thatNumericChunk = int.Parse(str2);
result = thisNumericChunk.CompareTo(thatNumericChunk);
}
else
{
result = str1.CompareTo(str2);
}
if (result != 0)
{
return result;
}
}
return len1 - len2;
}
}
这是我的脚本,其中包含附加到所有立方体的数组:
void Awake()
{
allCubes = GameObject.FindGameObjectsWithTag("cube");
allCubes = allCubes.OrderBy(obj => obj.name, new AlphanumComparatorFast()).ToArray();
}
这是检查器中的输出:
我的问题是:有没有办法找出数组中当前对象的编号?我将此脚本添加到所有立方体中,那么有没有一种方法可以让我在脚本中添加一些代码,它会返回该游戏对象在数组列表中的位置?例如,如果我调试 Cube5,它将返回:
我在数组中的位置是4
我的目标是获得每个立方体的下一个立方体的下一个立方体:)。
所以 Cube1 应该给我 Cube3,Cube3 应该给我 Cube5 等等。我想我可以使用答案然后这样做variable + 2。我想要这个,因为每个立方体都必须获取下一个立方体的下一个立方体的一些信息。
【问题讨论】:
-
听起来您想要维护一个链表,这取决于您的最终实现以及创建多维数据集时是否可以通过引用来链接多维数据集,这会快几个数量级。您可能只需遍历
FindGameObjects返回的多维数据集并在那里设置引用。