Swapping Objects

Hi

I am a COMPLETE CODER NOOB so be gentle.

Basically i have for now created a prefab. Of which at the beginning of the game 150 are created =) So what i want to do as a next step is swapping them.

This should work the following way: I click on object (Cube) and then it somehow saves the position of it and then when i click on the next one they swap positions. This would be best with if they would slowly move into thei new place instead of just being there but that would be the minor problem.

I am really lost what to do now. I looked through this forum and the documentation but didnt really find anything that suits my problem

Same advice as I always give: break it down into separate problems, and solve the problems one by one.

First, you need to be able to determine when an object has been clicked on. There are multiple ways to do that, but a fairly straightforward way is to give the object a collider and use OnMouseDown(). Start by writing a script that just prints "I was clicked!" or whatever to the console when an object is clicked on, just to make sure that part's working.

Then, you'll probably need a simple state machine. The FSM will only have two states, 'waiting for the first click', and 'waiting for the second click'.

When you first click on a box, you save a reference to the box that was clicked on, and change the state to 'waiting for the second click'. Then, on the next click, you swap the 'saved' box with the box that was just clicked. An example in pseudocode:

if mouse button was clicked
    if state == waiting for first click
        saved box = clicked box
        state = waiting for second click
    else if state == waiting for second click
        swap(saved_box, clicked box)
        state = waiting for first click
    end if
end if

You'll need to implement swap() of course. As for animating the effect, you could have a third state ('swapping boxes') or use a coroutine, and animate the effect using, for example, Vector3.Lerp() and an 'ease-in, ease-out' mapping function.

movement-wise, I would use itween (just google)

make sure to get the visual editor also

void OnMouseUp()
{
Vector3 temp = GameObject1.transform.position;
GameObject1.transform.position = GameObject2.transform.position;
GameObject2.transform.position = temp;
}
This will solve your Problem…If found useful then don’t forget to mark the answer…Cheers…Enjoy…