Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Script for weather changes

Discussion in 'Scripting' started by MaskyDEV, Nov 28, 2014.

  1. MaskyDEV

    MaskyDEV

    Joined:
    Nov 16, 2014
    Posts:
    10
    So I have made some different weather states, but I need a script to switch weather every so often. Btw I use javascript mostly
     
  2. fox4snce

    fox4snce

    Joined:
    Jan 25, 2014
    Posts:
    74
    The timer I generally use because it's simple is this: have a variable called oldTime, when a script starts, save Time.time as oldTime. Then for each update, check for Time.time - oldTime >= the amount of time you want to wait between changing the weather state.

    In c# it looks like this:


    Code (CSharp):
    1. public float oldTime;
    2.  
    3. void Start()
    4. {
    5.   oldTime = Time.time();
    6. }
    7.  
    8. void Update()
    9. {
    10.   if(Time.time - oldTime >= 5.0f)
    11.   {
    12.     changeWeatherState();
    13.  
    14.     // most important statement because you have to reset oldTime inside
    15.     // the if statement when the if statement is true.
    16.     oldTime = Time.time;
    17.   }
    18. }
    This is not the only way to do a timer... but it is very easy to understand.
     
  3. djfunkey

    djfunkey

    Joined:
    Jul 16, 2012
    Posts:
    201
    This is a pretty crude mockup of a timer script for you in UnityScript (I'm a C# coder). So some things might now work, since I havent tested it. But this should give you a general idea of what to do for your timer. You can change the lenght of the timer on the fly aswell which can come in handy sometimes.

    Code (JavaScript):
    1. public var timerLenght : float;
    2. private var timerTime : float;
    3.  
    4. function Update () {
    5.     timerTime += Time.deltaTime;
    6.     if (timerTime >= timerLenght) {
    7.         changeWeatherState();
    8.         timerTime = 0;
    9.     }
    10. }