- Home /
Alarm lights not changing
I've tried implementing some alarm lights in my game, that when set off, alternate in intensity. The problem is that they just stay static, not gettting more or less intense, whats wrong with my code? (c#)
using UnityEngine; using System.Collections; public class AlarmLight : MonoBehaviour { public float fadeSpeed = 2f; public float highIntensity = 2f; public float lowIntensity = 0.5f; //public float changeMargin = 0.2f; public bool alarmOn = true; private float targetIntensity; void Awake() { light.intensity = lowIntensity; targetIntensity = highIntensity; } void Update() { if(alarmOn == true) { if(light.intensity == highIntensity) { targetIntensity = lowIntensity; light.intensity = Mathf.Lerp (light.intensity, targetIntensity, fadeSpeed * Time.deltaTime); } //CheckTargetIntensity(); else if(light.intensity == lowIntensity) { targetIntensity = highIntensity; light.intensity = Mathf.Lerp (light.intensity, targetIntensity, fadeSpeed * Time.deltaTime); } } }
Answer by SkaredCreations · Mar 22, 2014 at 05:52 PM
First you should move the assignation of light.intensity value out of your "if" statements else it will be executed only when its exactly equals to "lowIntensity". Second you're using Lerp and it rarely arrives to the lowest/highest boundaries, most of time it will reach a very approximative near the boundaries but won't reach them.
So I suggest you to add a tolerance, the following works:
void Awake()
{
light.intensity = lowIntensity;
targetIntensity = highIntensity;
}
void Update()
{
if(alarmOn == true)
{
if(light.intensity >= highIntensity)
{
targetIntensity = lowIntensity - 0.1f;
}
else if (light.intensity <= lowIntensity)
{
targetIntensity = highIntensity + 0.1f;
}
light.intensity = Mathf.Lerp (light.intensity, targetIntensity, fadeSpeed * Time.deltaTime);
}
}
Thankyou sooo much! I never realised that about LERP, that explains everything, thanks again!
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
How to Set a bool to Individual Scenes (C#) 1 Answer
Make player not be seen by AI, when player in foilage and shadows. 1 Answer
Starting out C# help 2 Answers
Animation Scripting c# help 2 Answers