Alternativate for Day-Night Script

Hello,

Just had an alternative version of the Daycycle script for people to use if they want, I think it works the same, and only uses the update method:

public class DayNight : MonoBehaviour {

[Tooltip ("Number of minutes per second that pass, try 60")]
public float timeScale;

// Update is called once per frame
void Update () {
	transform.Rotate (Vector3.right / timeScale);
	
}

}

1 Like

Bit late, but figured I’d point out that while this script will allow you to achieve the same goal, it works quite differently. When you label timeScale as the minutes per second, you would expect a higher number would make the day pass by faster, as is the case in the code shown in the video. However in this code the higher you put this value the slower the sun would rotate. Secondly you don’t use Time.deltaTime, this means that if someone ran the game at 30 FPS, their sun would move half as fast as if someone ran the game at 60 FPS. Without using deltaTime the game doesn’t respond to different framerates.

So a fix to the equation would be:

public class DayNight : MonoBehaviour {
    [Tooltip ("Number of minutes that pass per second in game")]
    public float minutesPerSecond;
    
    void Update () {
        transform.Rotate (Vector3.right * 0.25f * Time.deltaTime * minutesPerSecond);
    }
}

This also only uses the Update function, but has the advantage that it does what the annotation says, higher values make time go by faster. At 60 a full day goes by in 24 seconds, as 60 minutes is 1 hour, 24 hours in 1 day. So 60 minutes per second is an hour per second. The code shown in the video wasn’t correct, as was noted in another post on this videos discussion. The disadvantage of this method is that that’s several multiplications per frame, utilizing the Start function to do some precalculations can be useful:

public class DayNight : MonoBehaviour {
    [Tooltip ("Number of minutes that pass per second in game")]
    public float minutesPerSecond;

    private Vector3 sunRotatePerSecond;
    void Start() {
        sunRotatePerSecond = Vector3.right * 0.25f * minutesPerSecond;
    }
    void Update() {
        transform.Rotate (sunRotatePerSecond * Time.deltaTime);
    }
}

That’s the advantage of a Start function, allowing calculations that don’t need data that will change between frames to be calculated once instead of every frame. Now if you wish to set it up to where the speed of the day can be changed, such that the minutes per second can change, then you either need to have a function to recalculate the value and call it every time you change the minutes per second, or you move that part out of the precalculations and calculate it every frame. Considering that Unity generated the Start function for you automatically upon script creation, there’s very little use in not using it when it provides a benefit.

3 Likes

Privacy & Terms