- Home /
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
Answer by fherbst · Jul 05, 2010 at 07:05 PM
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.
Thanks for your answer felix.
Unfortunately when I enter this into a Javascript I get the following error - "$$anonymous$$ Identifier : 'amountOfOn'. Am I doing something wrong here?
Thanks
Uh, I'm sorry, I had a wrong case on the second "of". I edited my post, I hope it works now!
So, could you mark the question as answered? Would be nice :).
Answer by Magnus Wolffelt · Aug 07, 2010 at 11:01 AM
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)); } }
Your answer
Follow this Question
Related Questions
C# GameObjects Instantiate Into Each Other Issue 1 Answer
GameObject variable change for all of the objects 1 Answer
Three Spots For Three Random Objects 1 Answer
Instantiate a GameObject at the position of one of its child objects 1 Answer
How to randomly spawn three non repeating gameobjects from an array? 2 Answers