How to increment a global counter variable (eg, a hit tally) and display in a GUIText

I would like to understand how I can update a GUI element (a kill tally). when an enemy is killed.

I think I would add some function to "CharacterDamage.js" and then have a script attached to a GUItext that would be able to know when the "CharacterDamage.js" did it thing.

I hope.

thank you, ken mcall

There are a few ways to go about this, depending on how you want to manage the structure of your project on a broad scale. I'm going to list from in order - quick'n'dirty first.

Quick'n'dirty way:

Assuming enemy characters all have the “CharacterDamage” script attached, add a private static variable called numKills, and a public GUIText var called killsDisplay.

private static var numKills : int;
var killsDisplay : GUIText;

Then use the editor to drag-reference the GUIText element into that var. Then, each time a kill is detected, increment the 'numKills' var, and update the display - directly from the CharacterDamage script:

killsDisplay.text = "Kills: "+numKills;

While this will work, it has drawbacks - mainly that it doesn't separate your "display" code from your game system code. This can cause problems as your project grows in complexity. It makes your code harder to re-use and to debug.

Longer, but better way:

A better way might be to have a script on th GUIText itself, which is responsible for counting kills and displaying them, and have the enemy class send a message to it. Eg, make a script called “KillsCounter”, and put it on the GUIText element. The “KillsCounter” script should look like this:

private var numKills= 0;

function Start()

function UpdateDisplay()
    guiText.text = "Kills: "+numKills;

function AddKill()

Then, in your enemy class, you just need a reference to the "KillsCounter" instance on the GUI element. Again, this could be created by using a dragged in reference. eg:

var killsCounter : KillsCounter;

// and then in the function where an enemy is killed:
function Kill() {

Even this method could become unwieldy if you have many different types of events, coming from many sources, which must be counted or reacted to. In this case, you'd probably be best off using some kind of Event manager. This is probably overkill if your only requirement is a kill counter, but usually in games you have many more events that you need to send and receive between your game entities.

Best Way:

Use an Event Manager (like this one on the wiki). I’m not going to go in to the details here, but the basic process is:

  • Have a script on your GUI Text sign up to recieve "enemy killed" events.
  • Have your enemy broadcast "enemy killed" events whenever an enemy is killed.

For more information about this, read that wiki page linked above, about the event manager.