SoFunction
Updated on 2025-03-08

Unity3D implements alarm light

This article shares the specific code of Unity3D implementation of alarm light for your reference. The specific content is as follows

Function introduction: The character enters a dangerous state and triggers the alarm light. The light turns on, gradually brightens, the brightness reaches the maximum value, and gradually becomes dark. The character is out of danger and the alarm light is turned off. At the same time, the alarm music is turned on and off.

1. First add an alarm light to the scene. (Alarm Light)
2. Set up its Transfrom, Tag, etc.
3. It is not enabled by default, and the Intensity value is 0. The color is generally dark red RGB (70,0,0).
Mask is Everyning, does not participate in baking, Mode is Realtime.

Add script:

public float fadeSpeed=2f; //Light brightness gradient speedpublic float highIntensity=4f; //Maximum brightnesspublic float highIntensity=0f; //Minimum brightness valuepublic float changeMargin=0.2f; //The sign that changes the target brightnesspublic bool alarmOn; //Whether to turn on the alarm lightprivate float targetIntensity; //Target brightness, towards changing brightnessprivate Light alarmLight; //Alarm light object 
void Awake(){
 alarmLight=GetComponent<Light>();
 =0; //The initial measurement is 0 targetIntensity=highIntensity; //The target is maximum brightness}
 
//Switch target brightnessvoid ChangeTargetIntensity(){
 if(()<changeMargin){
 if(targetIntensity==highTensity)
  targetIntensity=lowTensity;
 else 
  targetIntensity=highTensity;
 }
}
 
//Control the logic code to turn on the alarm lightvoid Update(){
 if(alarmLight){
 =(,targetIntensity,fadeSpeed*);
 ChangdeTargetIntensity();
 }else{
 =(,0f,fadeSpeed*);
 ChangdeTargetIntensity();
 }
}

ChangeTargetIntensity():The brightness of the alarm light changes toward the target brightness. When the current alarm light brightness reaches the maximum value, the target brightness becomes the minimum value. Conversely, when the current brightness is close to the minimum value, the target brightness becomes the maximum value.

Update():If the alarm is turned on, the brightness of the alarm light begins to change towards the target brightness.

static function Lerp ( from : float , to : float , t : float ) ;  float  Interpolation from the floating point number a to b in time t.

You can check AlarmOn in the Unity view. In other scripts, call the script AlarmOn to implement the alarm light switch.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.