Skip to content

Instantly share code, notes, and snippets.

@keiranlovett
Created October 17, 2013 10:33
Show Gist options
  • Save keiranlovett/7022666 to your computer and use it in GitHub Desktop.
Save keiranlovett/7022666 to your computer and use it in GitHub Desktop.
Light controller. Fades lights
// Converted from UnityScript to C# at http://www.M2H.nl/files/js_to_c.php - by Mike Hergaarden
// Do test the code! You usually need to change a few small bits.
using UnityEngine;
using System.Collections;
public class lightController : MonoBehaviour {
public bool flicker = false;
public float onTime = 2;
public float offTime = 2;
public float randomFlickerModifier = 0; // The flicker will vary from the given value in both positive and negative values
public bool dimming = false;// Set to true to activate lights that fade in and out
public float dimSpeed = 0.3f;// The speed which it dims
public float lowestIntesity = 0;// This is the lowest intensity the light will go to
public float highestIntesity = 3; // This is highest lowest intensity the light will go to
public bool varyRange = false;
public float maxRange;
public float minRange;
public float rangeSpeedChange = 1;
private int rangeState= 0; // 0 = getting darker, 1 = getting lighter.
private int lightState= 0; // 0 = getting darker, 1 = getting lighter.
private float nextFlicker = 0;
private Light thisLight;
void Awake (){
thisLight = gameObject.GetComponent<Light>(); // Store the light for faster performance
}
void Update (){
if (flicker)
{
if (Time.time > nextFlicker)
{
if (thisLight.enabled == true)
{
nextFlicker += offTime;
nextFlicker += Random.Range(-randomFlickerModifier, randomFlickerModifier);
thisLight.enabled = false;
}
else{
nextFlicker += onTime;
nextFlicker += Random.Range(-randomFlickerModifier, randomFlickerModifier);
thisLight.enabled = true;
}
}
}
if (dimming)
{
if (lightState == 0)
{
thisLight.intensity -= dimSpeed * Time.deltaTime;
if (thisLight.intensity <= lowestIntesity)
{
lightState = 1;
}
}
if (lightState == 1)
{
thisLight.intensity += dimSpeed * Time.deltaTime;
if (thisLight.intensity >= highestIntesity)
{
lightState = 0;
}
}
}
if (varyRange)
{
if (rangeState == 0)
{
thisLight.range -= rangeSpeedChange * Time.deltaTime;
if (thisLight.range <= minRange)
{
rangeState = 1;
}
}
if (rangeState == 1)
{
thisLight.range += rangeSpeedChange * Time.deltaTime;
if (thisLight.range >= maxRange)
{
rangeState = 0;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment