The standard answer for this seems to make a screen sized GUITexture and manipulate its Alpha.
Untiy 5 however has removed GUITexture from the object menu and marked it “legacy”.
This is what I tried, but it didn’t seem to work:
(1) Add a GUITexture component to my RigidBody FPS controller.
(2) Add a GUITextureLayer to my Rb FPS controller’s camera
Is this still the preferred method for flashing the entire screen to a given color? If so what else do I need to do to see the GUITexture?
If you have a Pro license(or using the 30day free trial) you have access to image post processing effects.
Otherwise you could use a cheap trick maybe by making a plane the child of the camera facing it and assign a material. Another thing is you can use the OnGUI to draw a rect on the screen and flash it.
I ended up solving it using GUI.DrawTexture. Code below.
using UnityEngine;
using System.Collections;
public class DamagedFlash : MonoBehaviour {
private Texture2D pixel;
public Color color = Color.red;
public float startAlpha=0.0f;
public float maxAlpha=1.0f;
public float rampUpTime=0.5f;
public float holdTime=0.5f;
public float rampDownTime=0.5f;
enum FLASHSTATE {OFF,UP,HOLD,DOWN}
Timer timer;
FLASHSTATE state = FLASHSTATE.OFF;
// Use this for initialization
void Start(){
pixel = new Texture2D(1,1);
color.a = startAlpha;
pixel.SetPixel(0,0,color);
pixel.Apply();
// for testing
//TookDamage(new DamagePacket(1));
}
public void Update() {
switch(state){
case FLASHSTATE.UP:
if (timer.UpdateAndTest()){
state =FLASHSTATE.HOLD;
timer = new Timer(holdTime);
}
break;
case FLASHSTATE.HOLD:
if (timer.UpdateAndTest()){
state =FLASHSTATE.DOWN;
timer = new Timer(rampDownTime);
}
break;
case FLASHSTATE.DOWN:
if (timer.UpdateAndTest()){
state =FLASHSTATE.OFF;
timer = null;
}
break;
}
}
private void SetPixelAlpha(float a){
color.a = a;
pixel.SetPixel(0,0,color);
pixel.Apply();
}
public void OnGUI(){
switch(state){
case FLASHSTATE.UP:
SetPixelAlpha(Mathf.Lerp(startAlpha,maxAlpha,timer.Elapsed));
break;
case FLASHSTATE.DOWN:
SetPixelAlpha(Mathf.Lerp(maxAlpha,startAlpha,timer.Elapsed));
break;
}
GUI.DrawTexture(new Rect(0,0,Screen.width, Screen.height), pixel);
}
public void TookDamage(DamagePacket dmg){
timer = new Timer(rampUpTime);
state = FLASHSTATE.UP;
}
}
The Timer class is a utility that looks like that.
using UnityEngine;
using System.Collections;
/***
* This class provides an in game loop timer mechanism
***/
public class Timer {
float _timeElapsed;
float _totalTime;
public Timer(float timeToCountInSec){
_totalTime = timeToCountInSec;
}
public bool UpdateAndTest(){
_timeElapsed+= Time.deltaTime;
return _timeElapsed>=_totalTime;
}
public float Elapsed{
get {return Mathf.Clamp(_timeElapsed/_totalTime,0,1);}
}
}
If you create an empty GameObject you can go Add Component > Rendering > GUI Texture.