room darkens

how can I do so that if an enemy comes against the room darkens slowly? I thought of a trigger and create a transparent plane. This is my code but it does not work. Tips?

#pragma strict


//Ogni volta che uno zombie collide con il protagonista per 1 secondo aumenta l'opacità
// della texture che simula il sangue. Al terzo contatto riparte il livello.


//script da applicare al protagonista


     var pianoTexture : GameObject;


function Start () {

pianoTexture = GameObject.FindGameObjectWithTag("pianoTexture");

pianoTexture.renderer.material.color.a =0;




}

function Update () {

}


function OnTriggerEnter(pippo:Collider){



   if(pippo.tag == "Finish"){
   print("COLLISIONE OK");

          /*   var tempo = 0;
             var max = 1.0;
             
             
             if(tempo>max)  { //0 > 1
             
               pianoTexture.renderer.material.color.a += 255.0;
               
               tempo = 0;
             
             
             
             }else{
             
             
             tempo += Time.deltaTime;
             
             
             }
             
             
             
*/
}


}

Depending on your platform choice, I wouldn’t recommend a semi-transparent image infront of the camera as that will up your drawcalls significantly - a better solution would be to dim the lights illuminating your scene.

However, if for some reason you don’t want to do that - here is a handy fader script that can be used to fade the material of a given object over a period of time.

(Remember that because this is an IEnumerator you will want to call it using Unity’s StartCoRoutine function. You will also need to be careful at some point later on in your script to stop the coroutine, otherwise you will have multiple unnecessary threads). For more information on using StartCoRoutine I’d recommend just searching for it on unity answers.

IEnumerator AlphaFadeTo(GameObject ObjectToFade, float FinalAlphaValue, float TotalFadeTime)
	{
		float alpha = transform.renderer.material.color.a;
		Color newColor = Color.white;
		for (float t = 0.0f; t <= 1.0f; t += Time.deltaTime / TotalFadeTime)
		{
			newColor = new Color(1, 1, 1, Mathf.Lerp(alpha,FinalAlphaValue,t));
			ObjectToFade.renderer.material.color = newColor;
			yield return null;
		}
		newColor.a = FinalAlphaValue;
		ObjectToFade.renderer.material.color = newColor;
	}