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 2018 Cookbook

You're reading from   Unity 2018 Cookbook Over 160 recipes to take your 2D and 3D game development to the next level

Arrow left icon
Product type Paperback
Published in Aug 2018
Publisher
ISBN-13 9781788471909
Length 794 pages
Edition 3rd Edition
Languages
Tools
Arrow right icon
Authors (2):
Arrow left icon
Matt Smith Matt Smith
Author Profile Icon Matt Smith
Matt Smith
Francisco Queiroz Francisco Queiroz
Author Profile Icon Francisco Queiroz
Francisco Queiroz
Arrow right icon
View More author details
Toc

Table of Contents (22) Chapters Close

Preface 1. Displaying Data with Core UI Elements FREE CHAPTER 2. Responding to User Events for Interactive UIs 3. Inventory UIs 4. Playing and Manipulating Sounds 5. Creating Textures, Maps, and Materials 6. Shader Graphs and Video Players 7. Using Cameras 8. Lights and Effects 9. 2D Animation 10. 3D Animation 11. Webserver Communication and Online Version-Control 12. Controlling and Choosing Positions 13. Navigation Meshes and Agents 14. Design Patterns 15. Editor Extensions and Immediate Mode GUI (IMGUI) 16. Working with External Resource Files and Devices 17. Working with Plain Text, XML, and JSON Text Files 18. Virtual Reality and Extra Features 19. Automated Testing 20. Bonus Chapters 21. Other Books You May Enjoy

Displaying a digital clock

Whether it is the real-world time, or 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:

Getting ready

For this recipe, we have prepared the font that you need in a folder named Fonts in the 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 the Text-clock GameObject 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

  1. 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+Alt and click on the top and center column rows.
  2. 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 Awake (){ 
    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'); } }
Underscore prefix so items appear first in sequence

Since scripts and scenes are things that are most often accessed, prefixing their folder names with an underscore character, _as _Scenes and _Scripts, means they are always at the top in the Project panel.
Although the preceding code is useful for illustrating how to access the time component of a DateTime object individually, the Format(...) method of the String class can be used to format a DateTime object all in a single statement, for example, the preceding could be written more succinctly in a single statement:
String.Format("HH:mm:ss", DateTime.Now)
For more examples, see http://www.csharp-examples.net/string-format-datetime/.
  1. Ensure the Text-clock GameObject is selected in the Hierarchy panel.
  2. In the Inspector panel, add an instance of the ClockDigital script class as a component by clicking the Add Component button, selecting Scripts, and choosing the Clock Digital script class:
Add script components through drag and drop

Script components can also be added to GameObjects via drag and drop. For example, with the Text-clock GameObject selected in the Hierarchy panel, drag your ClockDigital script onto it to add an instance of this script class as a component to the Text-clock GameObject.
  1. When you run the scene, you will now see a digital clock that shows hours, minutes, and seconds at the top-center part of the screen.

How it works...

You added a Text GameObject to a scene. You 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 the 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 Awake() 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. Storing a reference to a component in this way is referred to as caching—it means that code executed later does not need to repeat the computationally-expensive task of searching the GameObject hierarchy for a component of a particular type.

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 you don't want to miss.

The Unity tutorial for animating an analog clock

You have been reading a chapter from
Unity 2018 Cookbook - Third Edition
Published in: Aug 2018
Publisher:
ISBN-13: 9781788471909
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 €18.99/month. Cancel anytime