Unity.Tip – Create a Rotating Sun

Changing pace from the usual mobile app development, let’s talk about Unity!

Here’s a quick tip on adding a rotating sun to your Scenes to give your game a feeling of Day and Night.

First, add a light source or use the default light from a new scene, then Add a new Component .

Select Create new script and call it LightController. This script will have a public property for the length of the day you wish your sun to rotate, then handle the rotation speed calculation.

LightController.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class LightController : MonoBehaviour {
	public float DayLength;
	private float _rotationSpeed;

	void Update(){
		_rotationSpeed = Time.deltaTime / DayLength;
		transform.Rotate (0, _rotationSpeed, 0);
	}
}

Back in Unity, set your DayLength to a desired speed, and run your game.

Screen Shot 2017-05-30 at 5.02.35 PM
You’ll notice your sun/light moving around your scene and giving your area a sense of day and night.

If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.

Leave a comment