How to turn a light on and off randomly?

Hey,
So i’m trying to create a sheet lighting type of feel using a massive directional light. How do I program it so it randomly turns on and off rapidly 3 or 4 times? I’m using JavaScript.

http://docs.unity3d.com/Documentation/Manual/RandomNumbers.html

Try reading through the unity manual. it has lots of great answers to simple questions like this. unity answers is a good resource for technical questions that cannot be easily answered by looking at the docs or the forums, but most of the time either of those options is a beter bet.

var myLight : GameObject;

var randomThreshold : float;//don't touch
var minThreshold : float = 2.0;//minimum time between flashes
var maxThreshold : float = 6.0;//maximum time between flashes

var timer : float;//don't touch
var isFlashing : boolean;//don't touch

var randomFlashes : int;//don't touch
var minFlashes : int = 3;//minimum number of flashes
var maxFlashes : int = 5;//maximum number of flashes (maximum is exclusive!)

var timeBetweenFlashes : float = 0.1;//

function Start()
{
	randomThreshold = Random.Range(minThreshold, maxThreshold);
	randomFlashes = Random.Range(minFlashes, maxFlashes);
}

function Update()
{
	if(isFlashing == false)
	{
		timer += Time.deltaTime;
	}
	
	if(timer > randomThreshold)
	{
		timer = 0.0;
		FlashingLights();
	}
}

function FlashingLights()
{
	isFlashing = true;
	
	for(var x = 0; x < randomFlashes; x ++)
	{
		myLight.GetComponent(Light).enabled = false;
		yield WaitForSeconds(timeBetweenFlashes);
		myLight.GetComponent(Light).enabled = true;
		yield WaitForSeconds(timeBetweenFlashes);
	}
	
	//Reset variables for the next flashing
	randomThreshold = Random.Range(minThreshold, maxThreshold);
	randomFlashes = Random.Range(minFlashes, maxFlashes);
	
	
	isFlashing = false;
}

You can turn it on and off at random intervals with a coroutine, like this (attach it to the light game object):

private var flickering = false; // is true while flickering

function Flicker(howManyTimes: int){
  if (flickering) return; // abort further calls while running
  flickering = true;
  while (howManyTimes > 0){
    light.enabled = false; // turn off for a random time
    yield WaitForSeconds(Random.Range(0.1, 0.9);
    light.enabled = true; // turn on for another random time
    yield WaitForSeconds(Random.Range(0.1, 0.9);
    howManyTimes--; // repeat howManyTimes
  }
  light.enabled = false; // turn it off and return
  flickering = false; // Flicker finished
}

Call Flicker(4) to blink four times, for instance. It’s better to check whether it’s already running before calling Flicker in order to avoid unnecessary memory allocation:

if (!flickering) Flicker(4);