Game Development Reference
In-Depth Information
Listing 5-8. Displaying Textures
110 //------------------------------------------------
111 //ON GUI Function to show texture
112
void OnGUI()
113 {
114 if(
ShowDamage
){GUI.DrawTexture(ScreenRect,DamageTexture);}
115 }
//[…]
132 //------------------------------------------------
133
void Update()
134 {
135
//Build screen rect on update (in case screen size changes)
136 ScreenRect.x = ScreenRect.y = 0;
137 ScreenRect.width = Screen.width;
138 ScreenRect.height = Screen.height;
139 }
140 //------------------------------------------------
Here, the
Update
function is used to size a rectangle structure (
ScreenRect
) to the screen dimensions
(in pixels). This rect is updated on each frame, instead of being generated at application-start, since
it's possible, in some circumstances, for the display size to change during gameplay. For example,
the user could change the screen resolution or resize the game window. The
OnGUI
function is where
the texture is drawn or flashed to the display for a few seconds while damage is taken, using a call
to
GUI.DrawTexture
. The
OnGUI
function is called implicitly by Unity
several times per frame
. This
means
OnGUI
is usually called more regularly than
Update
, making it one of the most computationally
expensive events and a frequent source of performance problems. In short, you'll almost
never
want
to do anything in OnGUI, except draw graphical elements using the native
GUI
class. And there are
even developers who recommend never using OnGUI at all, even for
GUIs
. For my part, while the
GUI
class and
OnGUI
events can be useful for drawing limited GUIs (such as showing flashing red textures),
I almost never use it for GUIs, because I find it often causes performance issues on mobile devices.
Sometimes workarounds can be used, but later in this topic we'll see an alternative method for GUIs.
In this case, however, OnGUI can be used profitably to display a damage animation.
Note
Don't just take my word that this code works. Test it for yourself. Temporarily edit the
Update
event,
for example, so that a key press triggers the
ApplyDamage
event, to see the damage functionality in action!