Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Unity 5.x Cookbook

You're reading from   Unity 5.x Cookbook More than 100 solutions to build amazing 2D and 3D games with Unity

Arrow left icon
Product type Paperback
Published in Oct 2015
Publisher Packt
ISBN-13 9781784391362
Length 570 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Toc

Table of Contents (14) Chapters Close

Preface 1. Core UI – Messages, Menus, Scores, and Timers FREE CHAPTER 2. Inventory GUIs 3. 2D Animation 4. Creating Maps and Materials 5. Using Cameras 6. Lights and Effects 7. Controlling 3D Animations 8. Positions, Movement and Navigation for Character GameObjects 9. Playing and Manipulating Sounds 10. Working with External Resource Files and Devices 11. Improving Games with Extra Features and Optimization 12. Editor Extensions Index

Displaying a digital clock

Whether it is the real-world time, or perhaps an in-game countdown clock, many games are enhanced by some form of clock or timer display. The most straightforward type of clock to display is a string composed of the integers for hours, minutes, and seconds, which is what we'll create in this recipe.

The following screenshot shows the kind of clock we will be creating in this recipe:

Displaying a digital clock

Getting ready

For this recipe, we have prepared the font that you need in a folder named Fonts in the 1362_01_01 folder.

How to do it...

To create a digital clock, follow these steps:

  1. Create a new Unity 2D project.
  2. Import the provided Fonts folder.
  3. In the Hierarchy panel, add a UI | Text game object to the scene named Text-clock.
  4. Ensure that GameObject Text-clock is selected in the Hierarchy panel. Now, in Inspector, ensure that the following properties are set:
    • Text set to read as time goes here (this placeholder text will be replaced by the time when the scene is running.)
    • Font type set to Xolonium Bold
    • Font Size set to 20
    • Alignment set to horizontal and vertical center
    • Horizontal and Vertical Overflow settings set to Overflow
    • Color set to white
  5. Now, in the Rect Transform, click on the Anchor Presets square icon, which will result in the appearance of several rows and columns of preset position squares. Hold down SHIFT and ALT and click on the top and column center rows.
  6. Create a folder named Scripts and create a C# script class called ClockDigital in this new folder:
    using UnityEngine;
    using System.Collections;
    
    using UnityEngine.UI;
    using System;
    
    public class ClockDigital : MonoBehaviour {
      private Text textClock;
    
      void Start (){
        textClock = GetComponent<Text>();
      }
    
      void Update (){
        DateTime time = DateTime.Now;
        string hour = LeadingZero( time.Hour );
        string minute = LeadingZero( time.Minute );
        string second = LeadingZero( time.Second );
    
        textClock.text = hour + ":" + minute + ":" + second;
      }
    
      string LeadingZero (int n){
        return n.ToString().PadLeft(2, '0');
      }
    }
  7. With GameObject Text-clock selected in the Hierarchy panel, drag your ClockDigital script onto it to add an instance of this script class as a component to GameObject Text-clock, as shown in the following screenshot:
    How to do it...
  8. When you run the scene, you will now see a digital clock, showing hours, minutes, and seconds, at the top-center part of the screen.

How it works...

You added a Text GameObject to a scene. You have added an instance of the ClockDigital C# script class to that GameObject.

Notice that as well as the standard two C# packages (UnityEngine and System.Collections) that are written by default for every new script, you have added the using statements for two more C# script packages, UnityEngine.UI and System. The UI package is needed, since our code uses UI Text object; and the System package is needed, since it contains the DateTime class that we need to access the clock on the computer where our game is running.

There is one variable, textClock, which will be a reference to the Text component, whose text content we wish to update in each frame with the current time in hours, minutes, and seconds.

The Start() method (executed when the scene begins) sets the textClock variable to be a reference to the Text component in the GameObject, to which our scripted object has been added.

Note

Note that an alternative approach would be to make textClock a public variable. This will allow us to assign it via drag-and-drop in the Inspector panel.

The Update()method is executed in every frame. The current time is stored in the time variable, and strings are created by adding leading zeros to the number values for the hours, minutes, and seconds properties of variable time.

This method finally updates the text property (that is, the letters and numbers that the user sees) to be a string, concatenating the hours, minutes, and seconds with colon separator characters.

The LeadingZero(…)method takes as input an integer and returns a string of this number with leading zeros added to the left, if the value was less than 10.

There's more...

There are some details that you don't want to miss.

The Unity tutorial for animating an analogue clock

Unity has published a nice tutorial on how to create 3D objects, and animate them through C# script to display an analogue clock at https://unity3d.com/learn/tutorials/modules/beginner/scripting/simple-clock.

You have been reading a chapter from
Unity 5.x Cookbook
Published in: Oct 2015
Publisher: Packt
ISBN-13: 9781784391362
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime