Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Using Startcoroutine() in Update() function

Discussion in 'Scripting' started by brickT, Jan 25, 2016.

  1. brickT

    brickT

    Joined:
    Jul 1, 2015
    Posts:
    8
    Hello All,

    I want to use Startcoroutine() inside the Update() function. Though, I found on my search that, it is a good practice to use it in Start() function. But my game demands to execute it inside Update() function.

    My character starts moving automatically when clicks on Automatic button, and it should wait for 5 seconds, then it should again move and animate.

    But, the same is not happening. Any help would be appreciated.
     
  2. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    You've missed the point. If you use a coroutine directly in the Update function you start a new coroutine every frame. This often results in "strange behaviour". Lets say you're doing a "wait 1 sec then do" coroutine, if you start a new coroutine every frame you will get "wait one second then do the same thing every frame... over and over" which is obviously not the same.

    So long as there is some control in place (an if statement for example) that prevents a new coroutine being called every frame and only when it needs to be you can call a coroutine from anywhere, update included.
     
  3. TaleOf4Gamers

    TaleOf4Gamers

    Joined:
    Nov 15, 2013
    Posts:
    825
    You could use a mixture of things:
    If statement
    At the end of the coroutine you could have StopCoroutine("Name");
    A bool to see if it can proceed to start the coroutine.
     
  4. brickT

    brickT

    Joined:
    Jul 1, 2015
    Posts:
    8
    Hello All,
    I tried all sorts of things here, but I am not able to figure out what to do as I want my character to stop at one building for 5 seconds and then it should start moving. That's my main goal, whether, it can be achieved by using coroutine() or not.
    Any help or suggestions would be appreciated.
     
  5. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    lets see what you've got so far :)