Search Unity

  1. Get the latest news, tutorials and offers directly to your inbox with our newsletters. Sign up now.
    Dismiss Notice

How to make a prefab instantiate every 5 seconds.

Discussion in 'Scripting' started by General Jackson, Feb 4, 2012.

  1. General Jackson

    General Jackson

    Joined:
    Oct 31, 2009
    Posts:
    73
    Hi, I am trying to make a flash of lightning prefab spawn every five seconds. How would I go about doing this?
    Thanks,

    GJ
     
  2. HonorableDaniel

    HonorableDaniel

    Joined:
    Feb 28, 2007
    Posts:
    2,973
    Code (csharp):
    1. var flashPrefab : GameObject;
    2.  
    3. function Start () {
    4.    InvokeRepeating ("CreateLightning", 0.0f, 0.5f);
    5. }
    6.  
    7. function CreateLighting () {
    8.    Instantiate (flashPrefab);
    9. }
     
  3. Aniani

    Aniani

    Joined:
    Mar 17, 2011
    Posts:
    31
    There are also coroutines:

    Code (csharp):
    1.  
    2. var flashPrefab : GameObject;
    3.  
    4. function SpawnLightning()
    5. {
    6.     while( true )
    7.     {
    8.         yield WaitForSeconds(5.0);
    9.         Instantiate(flashPrefab);
    10.     }
    11. }
    12.  
     
  4. KrankyBoy

    KrankyBoy

    Joined:
    Mar 27, 2009
    Posts:
    734
    Just a quick note that Daniel's code will spawn lightning every half second not every 5 seconds.
     
  5. Tanel

    Tanel

    Joined:
    Aug 31, 2011
    Posts:
    508
    Also you might want to look into Random.Range. Might give it a more realistic feel.
     
unityunity