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

Pause in scripting

Discussion in 'Scripting' started by zreek17, Nov 8, 2013.

  1. zreek17

    zreek17

    Joined:
    Jun 2, 2013
    Posts:
    21
    Hello my friends! In creating my own Runner game I've faced some problems!

    Look at my script:
    Code (csharp):
    1.  
    2.         public Transform[] prefab = new Transform[12];
    3.     public Transform place;
    4.        
    5.     void Update()
    6.     {      
    7.         Vector3 CarPos = gameObject.transform.position;
    8.         CarPos.z = Monkey.distance + 30;
    9.        
    10.         Instantiate(prefab[Random.Range(0, 12)], CarPos, place.rotation);
    11.         // I want some pause here, about 3 seconds 
    12.                
    13.     }
    The point is, that these prefabs should appear in fornt of my runner - monkey. But because of Update function, they appear with every new frame. So I want to write something like: Pause 3seconds, and new object will appear 3 seconds later.
    So is it possible to make a pause in script?
     
  2. Marrrk

    Marrrk

    Joined:
    Mar 21, 2011
    Posts:
    1,032
    It is possible, do you know coroutines? You should read about them in case you do not know about them. They are a little bit tricky to use the first few times, but they will help you with what you want.

    Another hint: WaitForSeconds :)
     
  3. zreek17

    zreek17

    Joined:
    Jun 2, 2013
    Posts:
    21
    Well, coroutines can be used only in specific statements, if I'm not mistaken. But is it possible to use it in a simple script?
     
  4. Marrrk

    Marrrk

    Joined:
    Mar 21, 2011
    Posts:
    1,032
    It is, you dont even need the Update method for it, just call InvokeRepeating with your Coroutine and it should work.

    Your Coroutine may then look like something like this:

    Code (csharp):
    1.  
    2. void Do()
    3. {
    4.   Vector3 CarPos = gameObject.transform.position;
    5.   CarPos.z = Monkey.distance + 30;
    6.   Instantiate(prefab[Random.Range(0, 12)], CarPos, place.rotation);
    7. }
    8.  
     
  5. zreek17

    zreek17

    Joined:
    Jun 2, 2013
    Posts:
    21
    Sure, it is really awesome! Thank you very much!