Unity3D: Rising and Fading Text

In our current project, The Barn, we've found it very useful to display fading text over the character whenever something important happens - such as gaining life, becoming blinded, or being rooted, just to name a few.  To this end, I've written a fairly simple and powerful script to achieve the effect.  I call it: FadingMessage.

Oh great, rooted yet again.

Oh great, rooted yet again.


Initialization

As is often the case, before performing any logic we have to set things up.  The image below shows all of the variables to be used, with comments to describe what each variable does.

This is all fairly straightforward, especially with the comments.  However, when they get set is a bit tricky.  We will cover that later; for now let's take a look at the logic of the script.


Update Logic

Update is based on a timer (isn't everything in games, after all?), and slowly fades out the message by decreasing the current color's alpha value (_color.a).  It also rises the message over time by getting the in-world location and then translating it to on-screen location.  Once that's finished, it subtracts the raised amount from the initial y value, which moves the message up the screen over time.  The width and height values are simply static values, I just store them elsewhere (in a static GUIState class).


Update GUI

All of the heavy lifting is done in the Update method, all that OnGUI really has to do is take the results of its hard work and apply it to the GUI.

I mentioned earlier that setting the variables is a bit tricky.  Now that we know what the script actually does, let's take a look at how to call it.


Instantiation

We want to be able to create a message dynamically, so it can be used from anywhere in the game.  Making the variables public and setting them in the editor is not an option with this goal.  Instead, we have a public function that we can call from elsewhere in code:

This function can then be called from anywhere on a FadingMessage object as soon as it is initialized, and it will behave the same but with different parameters.  A quick way to do this is like so:

This simply creates a new object (named "message", though the name doesn't particularly matter) then adds the FadingMessage component to it.  Pretty simple!  Note that we don't have to use GameObject.Instantiate because we don't care where the object is placed, since it is simply a GUI element.


Conclusion

As stated earlier, this is a fairly simple script, but quite powerful as it can be called from anywhere in the code to display quick, concise information to the player.  And it even comes in all kinds of colors!