Search Unity

moving an object on button click

Discussion in 'Getting Started' started by skeleton-king, Aug 20, 2015.

  1. skeleton-king

    skeleton-king

    Joined:
    Nov 10, 2014
    Posts:
    63
    I wana move all childs in object by 180 in negative direction whenever i press my button.
    My code makes it snap to position instead of moving it smoothly.
    How do i move it smoothly

    Transform tm=pan.transform;

    foreach (Transform child in tm) {
    child.transform.Translate(-180,0,0));
    }
     
  2. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,859
    You'll have to move them just a little bit each time "Update" is called. (Or you could use a coroutine, but I don't recommend that, because they're hard to wrap your head around, and you've got enough problems on your hands already!)

    There are so-called "tweening" libraries like DOTween available to make this sort of thing easier, but I recommend you do it yourself so you can understand what's going on.

    So, when the button is clicked, set some "moving" flag. Then, in your Update method, you have code that looks something like this:

    Code (CSharp):
    1. if (moving) {
    2.     foreach (Transform child in tm) {
    3.         child.Translate(-5 * Time.deltaTime, 0, 0);
    4.     }
    5. }
    Then of course you will need to keep track of how much you've moved so you can figure out when to stop, but that's left as an exercise for the reader. :) Hopefully this will at least get you started — check out the coding tutorials at unity3d.com/learn for much more!