# How can I switch two GameObects in an array in Unity?

I'm putting together a match-3 as my first unity project and I'm having some trouble with switching two GameObjects. I thought I had it working, but I was running into strange issues. I hunted them down and found that my code below does NOT copy the script values of the original tiles when I instantiate them.

For instance, I switch a blue tile and a yellow tile. All stuff directly in the object instantiate correctly (right place, right color tile), but the code in my script that determines which it should be goes back to the default so behind the scenes they both think they are red tiles.

void SwitchTile(Vector2 start, Vector2 end)
{

GameObject tempStart = (GameObject)Instantiate(tiles[(int)start.x, (int)start.y]);
DestroyImmediate(tiles[(int)start.x, (int)start.y]);

tiles[(int)start.x, (int)start.y] = (GameObject)Instantiate(tiles[(int)end.x, (int)end.y]);
DestroyImmediate(tiles[(int)end.x, (int)end.y]);
tiles[(int)end.x, (int)end.y] = (GameObject)Instantiate(tempStart);

Destroy(tempStart);

}


How can I clone a GameObject with all of it's components also correctly cloned in unity? Or is there a better way of switching GameObjects in an array in unity?

• I don't know how you want this to work but are you sure you want to destroy and create new objects? SwitchTile sound more like you should just switch object positions without destroying or altering them. Why can't you just do sth like: tmp = array[x,y]; array[x,y] = array[x+1,y]; array[x+1,y] = tmp;? – NPS Mar 21 '14 at 0:06
• Funny story is, that's how I thought I should do it, but since I was new to unity I wasn't sure how the GameObjects worked with code. Followed an example that said I should do it as above. When I switched it back to what you suggest it worked fine. Want to make an official answer so I can mark it as one? – Califer Mar 21 '14 at 2:13
• Done. Btw post a link to "an example that said you should do it as above", I'm curious why they did it the way they did. As for GameObjects, they're internal Unity beings that are created with Instantiate() and destroyed with Destroy(). But most of the time you just want to manipulate with the references to them, not the objects themselves, which you do the same way as any other references in C#. – NPS Mar 21 '14 at 14:40
• My Google-fu skills are weak. I can't seem to find it anymore but instead I see stuff just like you mentioned. Wish I'd have seen that first. – Califer Mar 21 '14 at 23:49

You don't want to keep destroying and creating new objects. It's both more complicated than it should be and way less efficient. Instead you should just swap places of GameObjects (or more specifically of references to these objects) like this:
GameObject tmp = tiles[(int)start.x, (int)start.y];