• Home  / 
  • Unity3D
  •  /  Building Flappy Bird #8 – UGUI – Building the UI

Building Flappy Bird #8 – UGUI – Building the UI

Dragging Bubble to Scene

Welcome back!  In this section, we’ll add a scoring system.

 

The plan…

For our scoring system, we’ll use the bubble image we have in the art folder.

We’ll setup our game so that the player needs to pop bubbles for points.

To display the score, you’ll need UI components.  We’ll use the Unity3D UI system to accomplish this.

UGUI – The Unity3D GUI system

The Unity GUI system will allow us to easily draw text and graphics over our game.

Getting started with the GUI system is pretty simple, we just need to add a GUI game object.

Add a Text object by selecting GameObject->UI->Text

In your Hierarchy, you should see TWO new GameObjects.  There’s the Text that you added and a Canvas that is it’s parent.

The Canvas is the root of your UI, and all UI elements must be children of such a Canvas.

Because we didn’t already have a Canvas in our Scene, the editor automatically created one for us and added our new Text GameObject as a child.

In your game view, you should see our new Text object in the bottom left.

Let’s edit our Text object to say something more meaningful than “New Text”

With the Text GameObject selected, look at the Text component in the Inspector and notice the “Text” field.

Change it to say “Score: 0”

Anchoring

Right now, our UI component isn’t positioned correctly.  We could drag it around until it looks close, but right now it’s Anchored from the middle, so it would be at different areas depending on the screen size.  What we want for this game is to anchor the score text to the top left of the screen.  To accomplish this, we’ll use the “Anchor Presets”.

On the transform for the Text, click the Anchor tool (the red cross with a white box in the middle, the mouse is over it in the screenshot)

You’ll be presented with this dialog.

We want to select the top left point, but before you click it, notice the text at the top of the dialog.

For this UI component, we want to set the position along with the anchor, so before you click the pivot, hold the Alt key.

You should now notice your Score Text has moved to the top left corner of the screen.

Before we go too much further, let’s re-name the Text to something useful.

Change the name to “ScoreText”

Experiment

Try playing with the text component for a few minutes.

Adjust things like the font size, style, and color to get familiar with some of your options.

If you increase the font over 26, you’ll notice that it’s no-longer visible in your game view.

This is because the text is too large to fit into the component.  You can fix this by increasing the size of the text component.

Let’s Code

It’s time to hookup some code to make our score counter work.

The first thing we want to do is create a script to handle keeping score.

Create a new script named “ScoreKeeper”

Change the ScoreKeeper.cs file to look like this


using UnityEngine;
using UnityEngine.UI;

public class ScoreKeeper : MonoBehaviour
{
  private int _currentScore = 0;

  public void IncrementScore()
  {
    _currentScore++;
    Text scoreText = GetComponent<Text>();
    scoreText.text = "Score: " + _currentScore.ToString();
  } 

  void Update()
  {
    IncrementScore(); 
  } 
} 

Attach the “ScoreKeeper” script to the ScoreText GameObject

Before you hit play, look at the script and see if you can guess what it’s going to do.

 

Score Changing

Score Changing

 

Let’s inspect the different parts of this script to see what’s going on.

using UnityEngine.UI;

You’ve seen the “using” statements before.  What they do is tell the engine that we want to “use” components from that namespace.

In computing, a namespace is a set of symbols that are used to organize objects of various kinds, so that these objects may be referred to by name.

In this instance, we’re just telling Unity that we’ll be “using” UI components in our script.

private int _currentScore = 0;

Here, we’re defining a variable to hold our current score and setting it’s value to 0.


public void IncrementScore()
{
   _currentScore++;
   Text scoreText = GetComponent&amp;amp;amp;lt;Text&amp;amp;amp;gt;();
   scoreText.text = "Score: " + _currentScore.ToString();
}

The IncrementScore method does 3 things.

  • Adds one to the score using the ++ operator.  This could also be written as
    _currentScore = _currentScore + 1;
  • Gets the Text Component and assigns it to a local variable named “scoreText”
  • Sets the .text property of the “scoreText” object to have our new current score.

    ToString() gives us a text representation of a a non-text object

The last bit of code we have is the Update method.  All it’s doing is calling IncrementScore.  Because Update is called every frame, our IncrementScore method is called every frame, which in turn makes our score increase.  In this instance, the faster our game is running, the faster our score will increase.


void Update()
{
  IncrementScore();
}

The Update method is really just implemented so we can see something working.  For our game, we’ll have a more complicated scoring system, so let’s delete the Update method.

Change your ScoreKeeper script to look like this


using UnityEngine;
using UnityEngine.UI;

public class ScoreKeeper : MonoBehaviour
{
  private int _currentScore = 0;

  public void IncrementScore()
  {
    _currentScore++;
    Text scoreText = GetComponent<Text>();
    scoreText.text = "Score: " + _currentScore.ToString();
  }
}

 

Now that our code has changed, we need another way to call the IncrementScore method….

In comes the bubble

Look to your art folder in the Project View.

Drag a bubble from the Art folder into your scene.

Dragging Bubble to Scene

Dragging Bubble to Scene

Now, add a CircleCollider2D component to the newly placed bubble.

Check the IsTrigger box.

 

Let’s Code

We’ve got our bubble placed, but we really need to get some code in to make things work.

 

 

 

using UnityEngine;
public class Bubble : MonoBehaviour
{
  [SerializeField]
  private float _moveSpeed = 1f;

  // Update is called once per frame
  void Update()
  {
    transform.Translate(Vector3.up * Time.deltaTime * _moveSpeed);
    if (transform.position.y > 10)
    {
      Reset();
    }
  }

  void Reset()
  {
    transform.position = new Vector3(transform.position.x, -10, transform.position.z);
  }

  void OnTriggerEnter2D(Collider2D other)
  {
    if (OtherIsTheFish(other))
    {
      ScoreKeeper scoreKeeper = GameObject.FindObjectOfType<ScoreKeeper>();
      scoreKeeper.IncrementScore();
      Reset();
    }
  }

  bool OtherIsTheFish(Collider2D other)
  {
    return (other.GetComponent<Fish>() != null);
  }
}

Attach the bubble script to your bubble in the Hierarchy.

Now try playing and see if you can catch the bubble.

Cant catch the bubble

Cant catch the bubble

If you placed your bubble like I placed mine, it can’t be caught.

The reason for this is that we only ever change the Y position of the bubble, so it never moves past us.

Instead of adding more code to the bubble, we’ve got another trick we’ll be using.

Set the bubbles position to [2.5, -4, 0]

Now, make the bubble a child of the seaweed parent.

Bubble becoming a child of seaweed parent

Bubble becoming a child of seaweed parent

In the Inspector, hit the Apply button so that all our seaweed parents get a bubble.

Now give your game another play and enjoy your great work!

If all went well, it should look a bit like this

Popping Bubbles

Popping Bubbles

 

Next Up: We’ll randomize our bubbles, fix more bugs, and polish up our graphics (and maybe build out to a phone).