- Home /
Swap objects with same tag?
Hello, I have few random blocks. Some of them have same tag. Is it possible to swap position between 2 objects using their tag? for example:
GameObject.FindGameObjectsWithTag ("Blah");
//swap their position....how?
Comment
Best Answer
Answer by -hiTo- · Sep 01, 2013 at 02:19 PM
Absolutely.
Depending on how you want to switch them, you will need to make your own algorithm. But in it's simplest form;
GameObject[] blocks = GameObject.FindGameObjectsWithTag("Blah");
if (blocks.Length > 1) // No need to swap if there's only 1 or no objects
{
Vector3 tempPosition = new Vector3();
for (int i = 0; i < blocks.Length-1; i += 2)
{
tempPosition = blocks[i].transform.position;
blocks[i].transform.position = blocks[i+1].transform.position;
blocks[i+1].transform.position = tempPosition;
}
}
But, what is wrong here? When they swap, its object in objects?! function Swap() {
var blocks : GameObject[] = GameObject.FindGameObjectsWithTag("Selected");
if (blocks.Length > 1) // No need to swap if there's only 1 or no objects
{
blocks[blocks.Length-1].transform.position = blocks[0].transform.position; // Swap the last and the first object in the array
for (var i : int = 0; i < blocks.Length-2; i++) // -2 because we used the last array block already
{
temp.transform.position = blocks[i].transform.position;
blocks[i].transform.position = blocks[i+1].transform.position;
blocks[i+1].transform.position = temp.transform.position;
}
}
}