Move GameObject over time











up vote
4
down vote

favorite












I am learning Unity from a Swift SpriteKit background where moving a sprite's x Position is as straight forward as an running an action as below:



let moveLeft = SKAction.moveToX(self.frame.width/5, duration: 1.0)
let delayAction = SKAction.waitForDuration(1.0)
let handSequence = SKAction.sequence([delayAction, moveLeft])
sprite.runAction(handSequence)


I would like to know an equivalent or similar way of moving a sprite to a specific position for a specific duration (say, a second) with a delay that doesn't have to be called in the update function.










share|improve this question
























  • I highly recommend using an extension like iTween for this kind of controlled animations
    – caulitomaz
    Apr 25 '16 at 20:21






  • 1




    @caulitomaz Does not need iTween or plugin for that.He simply need to learn Coroutune.
    – Programmer
    Apr 25 '16 at 21:36








  • 1




    do not use iTween here, forget that.
    – Fattie
    Apr 26 '16 at 12:50










  • Hi @Nullititiousness. What you fundamentally have to get with is that Unity is a game engine, hence: is a frame based system. Everything is about frames. (Note indeed that in iOS, since it's not fundamentally frame based, they screw about and do things "frame-like" to compensate for the fact that it's just not a frame-based system, but sometimes you need things "like that".) In any event, if you say "I want to 'move' something". What are you actually saying? You're saying you want to do something every frame - right? If you start thinking that way it's easy.
    – Fattie
    Apr 26 '16 at 12:54















up vote
4
down vote

favorite












I am learning Unity from a Swift SpriteKit background where moving a sprite's x Position is as straight forward as an running an action as below:



let moveLeft = SKAction.moveToX(self.frame.width/5, duration: 1.0)
let delayAction = SKAction.waitForDuration(1.0)
let handSequence = SKAction.sequence([delayAction, moveLeft])
sprite.runAction(handSequence)


I would like to know an equivalent or similar way of moving a sprite to a specific position for a specific duration (say, a second) with a delay that doesn't have to be called in the update function.










share|improve this question
























  • I highly recommend using an extension like iTween for this kind of controlled animations
    – caulitomaz
    Apr 25 '16 at 20:21






  • 1




    @caulitomaz Does not need iTween or plugin for that.He simply need to learn Coroutune.
    – Programmer
    Apr 25 '16 at 21:36








  • 1




    do not use iTween here, forget that.
    – Fattie
    Apr 26 '16 at 12:50










  • Hi @Nullititiousness. What you fundamentally have to get with is that Unity is a game engine, hence: is a frame based system. Everything is about frames. (Note indeed that in iOS, since it's not fundamentally frame based, they screw about and do things "frame-like" to compensate for the fact that it's just not a frame-based system, but sometimes you need things "like that".) In any event, if you say "I want to 'move' something". What are you actually saying? You're saying you want to do something every frame - right? If you start thinking that way it's easy.
    – Fattie
    Apr 26 '16 at 12:54













up vote
4
down vote

favorite









up vote
4
down vote

favorite











I am learning Unity from a Swift SpriteKit background where moving a sprite's x Position is as straight forward as an running an action as below:



let moveLeft = SKAction.moveToX(self.frame.width/5, duration: 1.0)
let delayAction = SKAction.waitForDuration(1.0)
let handSequence = SKAction.sequence([delayAction, moveLeft])
sprite.runAction(handSequence)


I would like to know an equivalent or similar way of moving a sprite to a specific position for a specific duration (say, a second) with a delay that doesn't have to be called in the update function.










share|improve this question















I am learning Unity from a Swift SpriteKit background where moving a sprite's x Position is as straight forward as an running an action as below:



let moveLeft = SKAction.moveToX(self.frame.width/5, duration: 1.0)
let delayAction = SKAction.waitForDuration(1.0)
let handSequence = SKAction.sequence([delayAction, moveLeft])
sprite.runAction(handSequence)


I would like to know an equivalent or similar way of moving a sprite to a specific position for a specific duration (say, a second) with a delay that doesn't have to be called in the update function.







c# unity3d unity5






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jun 13 '17 at 17:56









Programmer

74.8k1080141




74.8k1080141










asked Apr 25 '16 at 20:17









Nullititiousness

86211




86211












  • I highly recommend using an extension like iTween for this kind of controlled animations
    – caulitomaz
    Apr 25 '16 at 20:21






  • 1




    @caulitomaz Does not need iTween or plugin for that.He simply need to learn Coroutune.
    – Programmer
    Apr 25 '16 at 21:36








  • 1




    do not use iTween here, forget that.
    – Fattie
    Apr 26 '16 at 12:50










  • Hi @Nullititiousness. What you fundamentally have to get with is that Unity is a game engine, hence: is a frame based system. Everything is about frames. (Note indeed that in iOS, since it's not fundamentally frame based, they screw about and do things "frame-like" to compensate for the fact that it's just not a frame-based system, but sometimes you need things "like that".) In any event, if you say "I want to 'move' something". What are you actually saying? You're saying you want to do something every frame - right? If you start thinking that way it's easy.
    – Fattie
    Apr 26 '16 at 12:54


















  • I highly recommend using an extension like iTween for this kind of controlled animations
    – caulitomaz
    Apr 25 '16 at 20:21






  • 1




    @caulitomaz Does not need iTween or plugin for that.He simply need to learn Coroutune.
    – Programmer
    Apr 25 '16 at 21:36








  • 1




    do not use iTween here, forget that.
    – Fattie
    Apr 26 '16 at 12:50










  • Hi @Nullititiousness. What you fundamentally have to get with is that Unity is a game engine, hence: is a frame based system. Everything is about frames. (Note indeed that in iOS, since it's not fundamentally frame based, they screw about and do things "frame-like" to compensate for the fact that it's just not a frame-based system, but sometimes you need things "like that".) In any event, if you say "I want to 'move' something". What are you actually saying? You're saying you want to do something every frame - right? If you start thinking that way it's easy.
    – Fattie
    Apr 26 '16 at 12:54
















I highly recommend using an extension like iTween for this kind of controlled animations
– caulitomaz
Apr 25 '16 at 20:21




I highly recommend using an extension like iTween for this kind of controlled animations
– caulitomaz
Apr 25 '16 at 20:21




1




1




@caulitomaz Does not need iTween or plugin for that.He simply need to learn Coroutune.
– Programmer
Apr 25 '16 at 21:36






@caulitomaz Does not need iTween or plugin for that.He simply need to learn Coroutune.
– Programmer
Apr 25 '16 at 21:36






1




1




do not use iTween here, forget that.
– Fattie
Apr 26 '16 at 12:50




do not use iTween here, forget that.
– Fattie
Apr 26 '16 at 12:50












Hi @Nullititiousness. What you fundamentally have to get with is that Unity is a game engine, hence: is a frame based system. Everything is about frames. (Note indeed that in iOS, since it's not fundamentally frame based, they screw about and do things "frame-like" to compensate for the fact that it's just not a frame-based system, but sometimes you need things "like that".) In any event, if you say "I want to 'move' something". What are you actually saying? You're saying you want to do something every frame - right? If you start thinking that way it's easy.
– Fattie
Apr 26 '16 at 12:54




Hi @Nullititiousness. What you fundamentally have to get with is that Unity is a game engine, hence: is a frame based system. Everything is about frames. (Note indeed that in iOS, since it's not fundamentally frame based, they screw about and do things "frame-like" to compensate for the fact that it's just not a frame-based system, but sometimes you need things "like that".) In any event, if you say "I want to 'move' something". What are you actually saying? You're saying you want to do something every frame - right? If you start thinking that way it's easy.
– Fattie
Apr 26 '16 at 12:54












3 Answers
3






active

oldest

votes

















up vote
13
down vote



accepted










gjttt1's answer is close but is missing important functions and the use of WaitForSeconds() for moving GameObject is unacceptable. You should use combination of Lerp, Coroutine and Time.deltaTime. You must understand these stuff to be able to do animation from Script in Unity.



public GameObject objectectA;
public GameObject objectectB;

void Start()
{
StartCoroutine(moveToX(objectectA.transform, objectectB.transform.position, 1.0f));
}


bool isMoving = false;

IEnumerator moveToX(Transform fromPosition, Vector3 toPosition, float duration)
{
//Make sure there is only one instance of this function running
if (isMoving)
{
yield break; ///exit if this is still running
}
isMoving = true;

float counter = 0;

//Get the current position of the object to be moved
Vector3 startPos = fromPosition.position;

while (counter < duration)
{
counter += Time.deltaTime;
fromPosition.position = Vector3.Lerp(startPos, toPosition, counter / duration);
yield return null;
}

isMoving = false;
}


Similar Question: SKAction.scaleXTo






share|improve this answer























  • Thanks! Can Vector3.Lerp also be used on a rotation, imagine if you want to also have the object rotate from startRotation to endRotation (x,y,z)
    – vikingsteve
    Jun 13 '17 at 12:06










  • @vikingsteve Yes. You can use Vector3.Lerp to change the transform.eulerAngles if it is an incremental rotation. If you just want to go from rotationA to rotationB then Quaternion.Lerp should be used to change transform.rotation. The rest of the code remains the-same. See my other answer for that solution.
    – Programmer
    Jun 13 '17 at 12:12






  • 1




    Thank you senpai!! Unity threads are sheit..
    – Isura Manchanayake
    Jun 28 '17 at 10:24


















up vote
3
down vote













The answer of git1 is good but there is another solution if you do not want to use couritines.



You can use InvokeRepeating to repeatedly trigger a function.



float duration; //duration of movement
float durationTime; //this will be the value used to check if Time.time passed the current duration set

void Start()
{
StartMovement();
}

void StartMovement()
{
InvokeRepeating("MovementFunction", Time.deltaTime, Time.deltaTime); //Time.deltaTime is the time passed between two frames
durationTime = Time.time + duration; //This is how long the invoke will repeat
}

void MovementFunction()
{
if(durationTime > Time.time)
{
//Movement
}
else
{
CancelInvoke("MovementFunction"); //Stop the invoking of this function
return;
}
}





share|improve this answer



















  • 1




    It's true that this works perfectly well, and everyone should learn to use InvokeRepeating. Normally, it's idiomatic to use a coroutine here.
    – Fattie
    Apr 26 '16 at 12:51


















up vote
1
down vote













You can use co-routines to do this. To do this, create a function that returns type IEnumerator and include a loop to do what you want:



private IEnumerator foo()
{
while(yourCondition) //for example check if two seconds has passed
{
//move the player on a per frame basis.
yeild return null;
}
}


Then you can call it by using StartCoroutine(foo())



This calls the function every frame but it picks up where it left off last time. So in this example it stops at yield return null on one frame and then starts again on the next: thus it repeats the code in the while loop every frame.



If you want to pause for a certain amount of time then you can use yield return WaitForSeconds(3) to wait for 3 seconds. You can also yield return other co-routines! This means the current routine will pause and run a second coroutine and then pick up again once the second co-routine has finished.



I recommend checking the docs as they do a far superior job of explaining this than I could here






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f36850253%2fmove-gameobject-over-time%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    3 Answers
    3






    active

    oldest

    votes








    3 Answers
    3






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    13
    down vote



    accepted










    gjttt1's answer is close but is missing important functions and the use of WaitForSeconds() for moving GameObject is unacceptable. You should use combination of Lerp, Coroutine and Time.deltaTime. You must understand these stuff to be able to do animation from Script in Unity.



    public GameObject objectectA;
    public GameObject objectectB;

    void Start()
    {
    StartCoroutine(moveToX(objectectA.transform, objectectB.transform.position, 1.0f));
    }


    bool isMoving = false;

    IEnumerator moveToX(Transform fromPosition, Vector3 toPosition, float duration)
    {
    //Make sure there is only one instance of this function running
    if (isMoving)
    {
    yield break; ///exit if this is still running
    }
    isMoving = true;

    float counter = 0;

    //Get the current position of the object to be moved
    Vector3 startPos = fromPosition.position;

    while (counter < duration)
    {
    counter += Time.deltaTime;
    fromPosition.position = Vector3.Lerp(startPos, toPosition, counter / duration);
    yield return null;
    }

    isMoving = false;
    }


    Similar Question: SKAction.scaleXTo






    share|improve this answer























    • Thanks! Can Vector3.Lerp also be used on a rotation, imagine if you want to also have the object rotate from startRotation to endRotation (x,y,z)
      – vikingsteve
      Jun 13 '17 at 12:06










    • @vikingsteve Yes. You can use Vector3.Lerp to change the transform.eulerAngles if it is an incremental rotation. If you just want to go from rotationA to rotationB then Quaternion.Lerp should be used to change transform.rotation. The rest of the code remains the-same. See my other answer for that solution.
      – Programmer
      Jun 13 '17 at 12:12






    • 1




      Thank you senpai!! Unity threads are sheit..
      – Isura Manchanayake
      Jun 28 '17 at 10:24















    up vote
    13
    down vote



    accepted










    gjttt1's answer is close but is missing important functions and the use of WaitForSeconds() for moving GameObject is unacceptable. You should use combination of Lerp, Coroutine and Time.deltaTime. You must understand these stuff to be able to do animation from Script in Unity.



    public GameObject objectectA;
    public GameObject objectectB;

    void Start()
    {
    StartCoroutine(moveToX(objectectA.transform, objectectB.transform.position, 1.0f));
    }


    bool isMoving = false;

    IEnumerator moveToX(Transform fromPosition, Vector3 toPosition, float duration)
    {
    //Make sure there is only one instance of this function running
    if (isMoving)
    {
    yield break; ///exit if this is still running
    }
    isMoving = true;

    float counter = 0;

    //Get the current position of the object to be moved
    Vector3 startPos = fromPosition.position;

    while (counter < duration)
    {
    counter += Time.deltaTime;
    fromPosition.position = Vector3.Lerp(startPos, toPosition, counter / duration);
    yield return null;
    }

    isMoving = false;
    }


    Similar Question: SKAction.scaleXTo






    share|improve this answer























    • Thanks! Can Vector3.Lerp also be used on a rotation, imagine if you want to also have the object rotate from startRotation to endRotation (x,y,z)
      – vikingsteve
      Jun 13 '17 at 12:06










    • @vikingsteve Yes. You can use Vector3.Lerp to change the transform.eulerAngles if it is an incremental rotation. If you just want to go from rotationA to rotationB then Quaternion.Lerp should be used to change transform.rotation. The rest of the code remains the-same. See my other answer for that solution.
      – Programmer
      Jun 13 '17 at 12:12






    • 1




      Thank you senpai!! Unity threads are sheit..
      – Isura Manchanayake
      Jun 28 '17 at 10:24













    up vote
    13
    down vote



    accepted







    up vote
    13
    down vote



    accepted






    gjttt1's answer is close but is missing important functions and the use of WaitForSeconds() for moving GameObject is unacceptable. You should use combination of Lerp, Coroutine and Time.deltaTime. You must understand these stuff to be able to do animation from Script in Unity.



    public GameObject objectectA;
    public GameObject objectectB;

    void Start()
    {
    StartCoroutine(moveToX(objectectA.transform, objectectB.transform.position, 1.0f));
    }


    bool isMoving = false;

    IEnumerator moveToX(Transform fromPosition, Vector3 toPosition, float duration)
    {
    //Make sure there is only one instance of this function running
    if (isMoving)
    {
    yield break; ///exit if this is still running
    }
    isMoving = true;

    float counter = 0;

    //Get the current position of the object to be moved
    Vector3 startPos = fromPosition.position;

    while (counter < duration)
    {
    counter += Time.deltaTime;
    fromPosition.position = Vector3.Lerp(startPos, toPosition, counter / duration);
    yield return null;
    }

    isMoving = false;
    }


    Similar Question: SKAction.scaleXTo






    share|improve this answer














    gjttt1's answer is close but is missing important functions and the use of WaitForSeconds() for moving GameObject is unacceptable. You should use combination of Lerp, Coroutine and Time.deltaTime. You must understand these stuff to be able to do animation from Script in Unity.



    public GameObject objectectA;
    public GameObject objectectB;

    void Start()
    {
    StartCoroutine(moveToX(objectectA.transform, objectectB.transform.position, 1.0f));
    }


    bool isMoving = false;

    IEnumerator moveToX(Transform fromPosition, Vector3 toPosition, float duration)
    {
    //Make sure there is only one instance of this function running
    if (isMoving)
    {
    yield break; ///exit if this is still running
    }
    isMoving = true;

    float counter = 0;

    //Get the current position of the object to be moved
    Vector3 startPos = fromPosition.position;

    while (counter < duration)
    {
    counter += Time.deltaTime;
    fromPosition.position = Vector3.Lerp(startPos, toPosition, counter / duration);
    yield return null;
    }

    isMoving = false;
    }


    Similar Question: SKAction.scaleXTo







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited May 23 '17 at 10:30









    Community

    11




    11










    answered Apr 25 '16 at 22:07









    Programmer

    74.8k1080141




    74.8k1080141












    • Thanks! Can Vector3.Lerp also be used on a rotation, imagine if you want to also have the object rotate from startRotation to endRotation (x,y,z)
      – vikingsteve
      Jun 13 '17 at 12:06










    • @vikingsteve Yes. You can use Vector3.Lerp to change the transform.eulerAngles if it is an incremental rotation. If you just want to go from rotationA to rotationB then Quaternion.Lerp should be used to change transform.rotation. The rest of the code remains the-same. See my other answer for that solution.
      – Programmer
      Jun 13 '17 at 12:12






    • 1




      Thank you senpai!! Unity threads are sheit..
      – Isura Manchanayake
      Jun 28 '17 at 10:24


















    • Thanks! Can Vector3.Lerp also be used on a rotation, imagine if you want to also have the object rotate from startRotation to endRotation (x,y,z)
      – vikingsteve
      Jun 13 '17 at 12:06










    • @vikingsteve Yes. You can use Vector3.Lerp to change the transform.eulerAngles if it is an incremental rotation. If you just want to go from rotationA to rotationB then Quaternion.Lerp should be used to change transform.rotation. The rest of the code remains the-same. See my other answer for that solution.
      – Programmer
      Jun 13 '17 at 12:12






    • 1




      Thank you senpai!! Unity threads are sheit..
      – Isura Manchanayake
      Jun 28 '17 at 10:24
















    Thanks! Can Vector3.Lerp also be used on a rotation, imagine if you want to also have the object rotate from startRotation to endRotation (x,y,z)
    – vikingsteve
    Jun 13 '17 at 12:06




    Thanks! Can Vector3.Lerp also be used on a rotation, imagine if you want to also have the object rotate from startRotation to endRotation (x,y,z)
    – vikingsteve
    Jun 13 '17 at 12:06












    @vikingsteve Yes. You can use Vector3.Lerp to change the transform.eulerAngles if it is an incremental rotation. If you just want to go from rotationA to rotationB then Quaternion.Lerp should be used to change transform.rotation. The rest of the code remains the-same. See my other answer for that solution.
    – Programmer
    Jun 13 '17 at 12:12




    @vikingsteve Yes. You can use Vector3.Lerp to change the transform.eulerAngles if it is an incremental rotation. If you just want to go from rotationA to rotationB then Quaternion.Lerp should be used to change transform.rotation. The rest of the code remains the-same. See my other answer for that solution.
    – Programmer
    Jun 13 '17 at 12:12




    1




    1




    Thank you senpai!! Unity threads are sheit..
    – Isura Manchanayake
    Jun 28 '17 at 10:24




    Thank you senpai!! Unity threads are sheit..
    – Isura Manchanayake
    Jun 28 '17 at 10:24












    up vote
    3
    down vote













    The answer of git1 is good but there is another solution if you do not want to use couritines.



    You can use InvokeRepeating to repeatedly trigger a function.



    float duration; //duration of movement
    float durationTime; //this will be the value used to check if Time.time passed the current duration set

    void Start()
    {
    StartMovement();
    }

    void StartMovement()
    {
    InvokeRepeating("MovementFunction", Time.deltaTime, Time.deltaTime); //Time.deltaTime is the time passed between two frames
    durationTime = Time.time + duration; //This is how long the invoke will repeat
    }

    void MovementFunction()
    {
    if(durationTime > Time.time)
    {
    //Movement
    }
    else
    {
    CancelInvoke("MovementFunction"); //Stop the invoking of this function
    return;
    }
    }





    share|improve this answer



















    • 1




      It's true that this works perfectly well, and everyone should learn to use InvokeRepeating. Normally, it's idiomatic to use a coroutine here.
      – Fattie
      Apr 26 '16 at 12:51















    up vote
    3
    down vote













    The answer of git1 is good but there is another solution if you do not want to use couritines.



    You can use InvokeRepeating to repeatedly trigger a function.



    float duration; //duration of movement
    float durationTime; //this will be the value used to check if Time.time passed the current duration set

    void Start()
    {
    StartMovement();
    }

    void StartMovement()
    {
    InvokeRepeating("MovementFunction", Time.deltaTime, Time.deltaTime); //Time.deltaTime is the time passed between two frames
    durationTime = Time.time + duration; //This is how long the invoke will repeat
    }

    void MovementFunction()
    {
    if(durationTime > Time.time)
    {
    //Movement
    }
    else
    {
    CancelInvoke("MovementFunction"); //Stop the invoking of this function
    return;
    }
    }





    share|improve this answer



















    • 1




      It's true that this works perfectly well, and everyone should learn to use InvokeRepeating. Normally, it's idiomatic to use a coroutine here.
      – Fattie
      Apr 26 '16 at 12:51













    up vote
    3
    down vote










    up vote
    3
    down vote









    The answer of git1 is good but there is another solution if you do not want to use couritines.



    You can use InvokeRepeating to repeatedly trigger a function.



    float duration; //duration of movement
    float durationTime; //this will be the value used to check if Time.time passed the current duration set

    void Start()
    {
    StartMovement();
    }

    void StartMovement()
    {
    InvokeRepeating("MovementFunction", Time.deltaTime, Time.deltaTime); //Time.deltaTime is the time passed between two frames
    durationTime = Time.time + duration; //This is how long the invoke will repeat
    }

    void MovementFunction()
    {
    if(durationTime > Time.time)
    {
    //Movement
    }
    else
    {
    CancelInvoke("MovementFunction"); //Stop the invoking of this function
    return;
    }
    }





    share|improve this answer














    The answer of git1 is good but there is another solution if you do not want to use couritines.



    You can use InvokeRepeating to repeatedly trigger a function.



    float duration; //duration of movement
    float durationTime; //this will be the value used to check if Time.time passed the current duration set

    void Start()
    {
    StartMovement();
    }

    void StartMovement()
    {
    InvokeRepeating("MovementFunction", Time.deltaTime, Time.deltaTime); //Time.deltaTime is the time passed between two frames
    durationTime = Time.time + duration; //This is how long the invoke will repeat
    }

    void MovementFunction()
    {
    if(durationTime > Time.time)
    {
    //Movement
    }
    else
    {
    CancelInvoke("MovementFunction"); //Stop the invoking of this function
    return;
    }
    }






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Apr 26 '16 at 12:51









    Fattie

    21.1k30198433




    21.1k30198433










    answered Apr 26 '16 at 9:01









    Mennolp

    241112




    241112








    • 1




      It's true that this works perfectly well, and everyone should learn to use InvokeRepeating. Normally, it's idiomatic to use a coroutine here.
      – Fattie
      Apr 26 '16 at 12:51














    • 1




      It's true that this works perfectly well, and everyone should learn to use InvokeRepeating. Normally, it's idiomatic to use a coroutine here.
      – Fattie
      Apr 26 '16 at 12:51








    1




    1




    It's true that this works perfectly well, and everyone should learn to use InvokeRepeating. Normally, it's idiomatic to use a coroutine here.
    – Fattie
    Apr 26 '16 at 12:51




    It's true that this works perfectly well, and everyone should learn to use InvokeRepeating. Normally, it's idiomatic to use a coroutine here.
    – Fattie
    Apr 26 '16 at 12:51










    up vote
    1
    down vote













    You can use co-routines to do this. To do this, create a function that returns type IEnumerator and include a loop to do what you want:



    private IEnumerator foo()
    {
    while(yourCondition) //for example check if two seconds has passed
    {
    //move the player on a per frame basis.
    yeild return null;
    }
    }


    Then you can call it by using StartCoroutine(foo())



    This calls the function every frame but it picks up where it left off last time. So in this example it stops at yield return null on one frame and then starts again on the next: thus it repeats the code in the while loop every frame.



    If you want to pause for a certain amount of time then you can use yield return WaitForSeconds(3) to wait for 3 seconds. You can also yield return other co-routines! This means the current routine will pause and run a second coroutine and then pick up again once the second co-routine has finished.



    I recommend checking the docs as they do a far superior job of explaining this than I could here






    share|improve this answer



























      up vote
      1
      down vote













      You can use co-routines to do this. To do this, create a function that returns type IEnumerator and include a loop to do what you want:



      private IEnumerator foo()
      {
      while(yourCondition) //for example check if two seconds has passed
      {
      //move the player on a per frame basis.
      yeild return null;
      }
      }


      Then you can call it by using StartCoroutine(foo())



      This calls the function every frame but it picks up where it left off last time. So in this example it stops at yield return null on one frame and then starts again on the next: thus it repeats the code in the while loop every frame.



      If you want to pause for a certain amount of time then you can use yield return WaitForSeconds(3) to wait for 3 seconds. You can also yield return other co-routines! This means the current routine will pause and run a second coroutine and then pick up again once the second co-routine has finished.



      I recommend checking the docs as they do a far superior job of explaining this than I could here






      share|improve this answer

























        up vote
        1
        down vote










        up vote
        1
        down vote









        You can use co-routines to do this. To do this, create a function that returns type IEnumerator and include a loop to do what you want:



        private IEnumerator foo()
        {
        while(yourCondition) //for example check if two seconds has passed
        {
        //move the player on a per frame basis.
        yeild return null;
        }
        }


        Then you can call it by using StartCoroutine(foo())



        This calls the function every frame but it picks up where it left off last time. So in this example it stops at yield return null on one frame and then starts again on the next: thus it repeats the code in the while loop every frame.



        If you want to pause for a certain amount of time then you can use yield return WaitForSeconds(3) to wait for 3 seconds. You can also yield return other co-routines! This means the current routine will pause and run a second coroutine and then pick up again once the second co-routine has finished.



        I recommend checking the docs as they do a far superior job of explaining this than I could here






        share|improve this answer














        You can use co-routines to do this. To do this, create a function that returns type IEnumerator and include a loop to do what you want:



        private IEnumerator foo()
        {
        while(yourCondition) //for example check if two seconds has passed
        {
        //move the player on a per frame basis.
        yeild return null;
        }
        }


        Then you can call it by using StartCoroutine(foo())



        This calls the function every frame but it picks up where it left off last time. So in this example it stops at yield return null on one frame and then starts again on the next: thus it repeats the code in the while loop every frame.



        If you want to pause for a certain amount of time then you can use yield return WaitForSeconds(3) to wait for 3 seconds. You can also yield return other co-routines! This means the current routine will pause and run a second coroutine and then pick up again once the second co-routine has finished.



        I recommend checking the docs as they do a far superior job of explaining this than I could here







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Apr 25 '16 at 20:50

























        answered Apr 25 '16 at 20:34









        Danny Herbert

        1,5301021




        1,5301021






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f36850253%2fmove-gameobject-over-time%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Full-time equivalent

            Bicuculline

            さくらももこ