Search Unity

  1. Unity 2020.1 has been released.
    Dismiss Notice
  2. We are looking for feedback on the experimental Unity Safe Mode which is aiming to help you resolve compilation errors faster during project startup.
    Dismiss Notice
  3. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    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,965
    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:
    733
    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