Lightning with random intervals

Hi there,

I'm pretty new to Unity, I mean i'v only been using it for about a year now and have started to learn the basics thoroughly. I'm trying to work out what would be the best way to create lightning in the level. The skybox I haven't completed yet, but will be a dark night sky. I want it so that a light will quickly flicker on and off at random intervals. Is it possible to do this? and if so how?

Thanks,

Alex

You can adapt this one (add it to a light):

var amountOfOff = 0.001;
var amountOfOn = 0.01;

function Update()
{
  if(enabled && (Random.value > amountOfOff))
    enabled = false;
  else
  if(Random.value > amountOfOn)
    enabled = true;
}

This will give you a light going on and off at random intervals. You will have to change the probability for going on and off, I didn't test these values. Right now its more probable that the light is going on, so the off-phases are shorter than the on-phases.

(Maybe you should put it in FixedUpdate or use something else to get it time-based, right now it will flicker different on faster/slower machines.)

There are for sure other/better ways to do this, but this was my first idea.

In my opinion this is better implemented with a coroutine, which gives you more control in a very simple way:

public float offDurationMin;
public float offDurationMax;

public float onDurationMin;
public float onDurationMax;

void Start() {
  StartCoroutine(DoOnOff());
}

IEnumerator DoOnOff() {
  while(true) {
    enabled = false;
    yield return new WaitForSeconds(Random.Range(offDurationMin, offDurationMax));
    enabled = true;
    yield return new WaitForSeconds(Random.Range(onDurationMin, onDurationMax));
  }
}