unity Gameobject数组互换交换位置并显示原来的位置
时间: 2024-01-08 16:04:06 浏览: 31
如果你想要每个GameObject在数组中原来的位置上显示,你可以在交换GameObject之前先记录它们在数组中的索引,然后在更新GameObject的位置时使用这些索引。以下是代码示例:
```
// 假设你有一个GameObject数组叫做gameObjects
int index1 = 0; // 第一个GameObject的索引
int index2 = 1; // 第二个GameObject的索引
// 记录两个GameObject在数组中的索引
int tempIndex1 = index1;
int tempIndex2 = index2;
// 交换两个GameObject的位置
GameObject temp = gameObjects[index1];
gameObjects[index1] = gameObjects[index2];
gameObjects[index2] = temp;
// 更新数组中GameObject的位置
for (int i = 0; i < gameObjects.Length; i++) {
// 使用之前记录的索引来更新GameObject的位置
if (i == tempIndex1) {
gameObjects[i].transform.position = new Vector3(tempIndex2 * 2, 0, 0);
} else if (i == tempIndex2) {
gameObjects[i].transform.position = new Vector3(tempIndex1 * 2, 0, 0);
} else {
gameObjects[i].transform.position = new Vector3(i * 2, 0, 0);
}
}
```
在这个例子中,我们首先记录了要交换的两个GameObject在数组中的索引`tempIndex1`和`tempIndex2`,然后交换它们的位置。在更新GameObject的位置时,我们使用之前记录的索引来判断哪一个GameObject应该在哪个位置上,而其他GameObject则按照它们在数组中的位置更新它们的位置。这样,每个GameObject就可以在它们原来的位置上显示了。