- Home /
How to swap 2 objects place with each other.(c#)
Hey I have been looking for a way to swap 2 objects place with each other, but haven't found anything that does that. Lets say there is a board with 5x5 squares on it(the squares are 1x1). On every square there is a gameobject. What I want is when I click on one game object, I can then click on one of the others to swap their place with each other. If anyone knows of a tutorial that deals with this kind of stuff, please tell me.
Answer by iwaldrop · Feb 01, 2013 at 09:54 PM
Transform t = targetGameObject.transform;
gameObjectToMove.transform.position = t.position;
or, on the GameObject,
transform.position = targetTransform.position;
All the above says is that you want to set the transform of a GameObject to another transform. This will instantly 'teleport' that object to that position, rotation, and scale. If you don't want to apply the rotation or scale, just use it's position (a Vector 3).
What you need to know if you want to do this is where the "other" object is and set your position to that other object. An object's position is stored in it's transform. So just get a reference to that other transform or, best case, have a controller handle moving things around.
void $$anonymous$$ovePieceToLocation(GameObject objectTo$$anonymous$$ove, GameObject objectDestination, bool destroyDestinationObject)
{
// set position
objectTo$$anonymous$$ove.transform.position = objectDestination.transform.position;
// set rotation
objectTo$$anonymous$$ove.transform.rotation = objectDestination.transform.rotation;
// set scale
objectTo$$anonymous$$ove.transform.scale = objectDestination.transform.scale;
if(destroyDestinationObject)
Destroy(objectDestination);
}
All you're doing is handling the repositioning of one object to the old object's position and then optionally destroying the old one. You could also just turn off the old GameObject, or move the old one to the former's position (transposing them).
Let me know if you have more questions, and use the 'add new comment' button! :)
You cannot assign to transform
. What you mean is transform.position
, and if you need to take care of the orientation, too, similar for transform.rotation
.
Indeed, wolfram! I guess that explains why I never do it...
There is no transform.scale, you'll have to use transform.localScale ins$$anonymous$$d.
lol...guess that's what I get for trying to answer and work at the same time!
Answer by StianH · Feb 01, 2013 at 10:17 PM
I don't have much knowledge when it comes to scripting, if it isn't to much to ask, could you elaborate a little on that?
Sure. But, first, you commented using the answer field. Please, in the future, use the add a new comment button where you're trying to comment. I'll elaborate there.