Reader small image

You're reading from  Unity Cookbook - Fifth Edition

Product typeBook
Published inNov 2023
Reading LevelIntermediate
PublisherPackt
ISBN-139781805123026
Edition5th Edition
Languages
Tools
Right arrow
Authors (3):
Shaun Ferns
Shaun Ferns
author image
Shaun Ferns

Shaun is a lecturer at Technological University Dublin. He is currently teaching on the BA (Hons) in Creative Digital Media where he is lead in the delivery of the Multimedia Stream. He is currently exploring serious games for construction-related training as well as the opportunities transmedia provides in improving user experience and engagement in cultural archive artifacts. His educational research is currently driven by his interest in self-determined learning (heutagogy), rhizomatic learning theory, micro-credentialing /digital badging, and curriculum development.
Read more about Shaun Ferns

Sinéad Murphy
Sinéad Murphy
author image
Sinéad Murphy

Sinead Murphy is currently Data Analytics Manager for the Irish NGO Trocaire. She has over 25 years of computing experience, including freelance IT training and database consulting, university lecturing in mathematics, IT skills and programming at TU Dublin (Ireland) and Middlesex University (London). She is a published academic, with undergraduate and postgraduate degrees in mathematics, computing and data science. She is passionate about the use of IT for understanding and visualising data, and using that understanding to make meaningful differences in the world. She is currently exploring the use of Python and Unity for data analytics and interactive visualisations.
Read more about Sinéad Murphy

View More author details
Right arrow

Advanced Topics – Gizmos, Automated Testing, and More

This chapter will cover three sets of advanced recipes:

  • Gizmos
  • Automated testing
  • An introduction to Unity Python

Gizmos facilitate Unity Editor customization. Gizmos are visual aids for game designers that are provided in the Scene panel. They can be useful as setup aids (to help us know what we are doing) or for debugging (understanding why objects aren’t behaving as expected).

Gizmos are not drawn through Editor Scripts, but as part of the MonoBehaviour class, so they only work for GameObjects in the current scene. Gizmo drawing is usually performed with two methods:

  • OnDrawGizmos(): This is executed at every frame or Editor window repaint, for every GameObject in the Hierarchy panel.
  • OnDrawGizmosSelect(): This is executed at every frame, for just the GameObject(s) that is currently selected in the Hierarchy panel.

Gizmo graphical drawing makes it simple...

Using a gizmo to show the currently selected object in the Scene panel

Gizmos are visual aids that are provided to game designers in the Scene panel. In this recipe, we’ll highlight the GameObject that is currently selected in the Hierarchy panel in the Scene panel.

Figure 19.2: Wireframe spheres around the selected GameObject

How to do it...

To create a gizmo to show the selected object in the Scene panel, follow these steps:

  1. Create a new Unity 3D project.
  2. Create a 3D Cube by going to Create | 3D Object | Cube.
  3. Create a C# script class called GizmoHighlightSelected and add an instance object as a component to the 3D Cube:
    using UnityEngine;
    public class GizmoHighlightSelected : MonoBehaviour {
        public float radius = 5.0f;
        void OnDrawGizmosSelected() {
            Gizmos.color = Color.red;
            Gizmos.DrawWireSphere(transform.position, radius);
            Gizmos.color = Color.yellow;
            Gizmos.DrawWireSphere(transform...

Creating an Editor snap-to-grid drawn by a gizmo

If the positions of objects need to be restricted to specific increments, it is useful to have a grid drawn in the Scene panel to help ensure that new objects are positioned based on those values, as well as code to snap objects to that grid.

In this recipe, we’ll use gizmos to draw a grid with a customizable grid size, color, number of lines, and line length. The result of following this recipe will look as follows:

Figure 19.3: Example of a visible grid to which objects have been snapped

How to do it...

To create an Editor snap-to-grid drawn by a gizmo, follow these steps:

  1. Create a new Unity 3D project.
  2. In the Scene panel, turn off the Skybox view (or simply toggle off all the visual settings) so that you have a plain background for your grid:

Figure 19.4: Turning off the Skybox view in the Scene panel

  1. Updating the display and the child objects will be performed...

Generating and running a default test script class

Unity can create a default C# test script for you, thereby enabling you to quickly start creating and executing tests on your project. In this recipe, we will add the Unity Test Framework to a project and use it to automatically generate a default test script for us. This will be the basis for several of the following recipes:

Figure 19.7: Tests passing (indicated by green ticks)

How to do it...

To generate a default test script class, follow these steps:

  1. Create a new 3D Unity project.
  2. Display the Test Runner panel by going to Window | General | Test Runner.

Figure 19.8: The Test Runner panel

  1. Ensure that the EditMode button is selected in the Test Runner panel.
  2. In the Test Runner panel, click the Create EditMode Test Assembly Folder button. You’ll now see a folder called Tests that’s been created in the Project panel.
  3. Select the Tests folder.
  4. ...

Making a simple unit test

In the same way as printing “hello world” is most programmers’ first program statement, asserting that 1 + 1 = 2 is perhaps the most common first test that’s executed for those learning unit testing. That’s what we’ll create in this recipe:

Figure 19.9: Our simple numeric test method passing with a green tick

How to do it...

To create and execute a simple unit test, follow these steps:

  1. Create a new 3D Unity project.
  2. Display the Test Runner panel by going to Window | General | Test Runner.
  3. Ensure that the EditMode button is selected in the Test Runner panel.
  4. In the Test Runner panel, click the Create EditMode Test Assembly Folder button. You’ll now see a folder called Tests that’s been created in the Project panel.
  5. Select the Tests folder.
  6. In the Test Runner panel, click the Create Test Script in current folder button.
  7. You should now have...

Parameterizing tests with a DataProvider

If we are testing our code using a range of test data, then sometimes, there is little difference between each test apart from the values. Rather than duplicating our Arrange/Act/Assert statements, we can reuse a single method, and the Unity Test Runner will loop through a collection of test data, running the test method for each set of test data. The special method that provides multiple sets of test data to a test method is known as a DataProvider, and we’ll create one in this recipe:

Figure 19.11: Running the test method with many sets of values with a DataProvider method

How to do it...

To parameterize tests with a DataProvider method, follow these steps:

  1. Create a new 3D Unity project.
  2. Display the Test Runner panel by going to Window | General | Test Runner.
  3. Ensure that the EditMode button is selected in the Test Runner panel.
  4. In the Test Runner panel, click the Create EditMode Test Assembly...

Unit testing a simple health script class

Let’s create something that might be used in a game and that can easily be unit tested. Classes that do not subclass from MonoBehaviour are much easier to unit test since instance objects can be created using the new keyword. If the class is carefully designed with private data and public methods with clearly declared dependencies as parameters, it becomes easy to write a set of tests to make us confident that objects of this class will behave as expected in terms of default values, as well as valid and invalid data.

In this recipe, we will create a health script class and a set of tests for this class. This kind of class can be reused for both the health of human players and Artificial Intelligence (AI)-controlled enemies in a game:

Figure 19.12: Passing tests for our health script class

How to do it...

To unit test a health script class, follow these steps:

  1. Create a new 3D Unity project.
  2. Create...

Creating and executing a unit test in PlayMode

It’s a good idea to write as much of the logic for a game as isolated, non-MonoBehaviour classes that are easy to unit test in EditMode as possible.

However, some of the logic in a game relates to things that happen when the game is running. Examples include physics, collisions, and timing-based events. We test these parts of our games in PlayMode.

In this recipe, we’ll create one very simple PlayMode test to check that the physics affect a Rigidbody (based on an example from the Unity documentation):

Figure 19.16: Running a physics PlayMode test

How to do it...

To create and execute a unit test in PlayMode, follow these steps:

  1. Create a new 3D Unity project.
  2. Display the Test Runner panel by going to Window | General | Test Runner.
  3. Ensure that the PlayMode button is selected in the Test Runner panel.
  4. In the Test Runner panel, click the Create PlayMode Test Assembly Folder...

PlayMode testing a door animation

Having learned the basics of PlayMode testing in the previous recipe, let’s test something non-trivial that we might find in a game. In this recipe, we’ll create a PlayMode test to ensure that a door opening animation plays when the player’s sphere object enters a collider.

A scene has been provided with the player’s sphere initialized to roll toward a red door. When the sphere hits the collider (the OnTriggerEnter event), some code sets the door’s Animator Controller Opening variable to true, which transitions the door from its closed state to its open state, as shown in the following screenshot:

Figure 19.18: The door will open (upward) when hit by the sphere

Thanks to the creator of the ground texture; it was designed by Starline and published at freepik.com.

Getting ready

For this recipe, a Unity package has been provided (doorScene.unitypackage) in the 19_07 folder.

How to do it...

PlayMode and unit testing a player health bar with events, logging, and exceptions

In this recipe, we will combine many different kinds of tests for a feature that’s included in many games – a visual health bar representing the player’s numeric health value (in this case, a float number from 0.0 to 1.0). Although it doesn’t comprehensively test all aspects of the health bar, this recipe will provide a good example of how we can go about testing many different parts of a game using the Unity testing tools.

A Unity package has been provided that contains the following:

  • Player.cs: A player script class for managing values for player health that uses delegates and events to publish health changes to any listening View classes.
  • Two View classes that register to listen for player health change events:
    • HealthBarDisplay.cs: This updates fillAmount for a UI image for each new player health value that’s received.
    • HealthChangeLogger...

Reporting Code Coverage testing

A useful tool in projects with code testing is to be able to analyze how much of a C# script class is being tested. For example, is every method being tested with at least one set of test data? Unity now offers a Code Coverage feature, which we’ll explore in this code-testing recipe. As shown in the following screenshot, Unity allows us to create a set of HTML pages for documenting the code coverage of tests against C# code.

With this, we can see what percentage of our code is covered by tests, and even which lines of code are, and are not, covered by our tests:

Figure 19.22: Code Coverage HTML report for the Player script class

Getting ready

This project builds on the previous one, so make a copy of what you made in that recipe and work on the copy.

How to do it...

To add Code Coverage reporting to a project with unit tests, follow these steps:

  1. Open the Code Coverage window by going to Window | Analysis...

Running simple Python scripts inside Unity

Unity Python is a package that allows Python code to be executed as part of a Unity project. In this recipe, we’ll install the package, test the Python Script Editor window with a traditional Hello World Python print statement, and create C# scripts to run Python based on the examples provided by Unity at https://docs.unity3d.com/Packages/com.unity.scripting.python@4.0/manual/inProcessAPI.html.

How to do it...

To run simple Python scripts inside Unity, follow these steps:

  1. Create a new 2D project.
  2. Open the Package Manager by navigating to Window | Package Manager.
  3. Set the list of packages to those in the Unity Registry and search for Python Scripting. Then, click Install.

Figure 19.24: Adding the Python Scripting package to a project

  1. Open the Python Script Editor panel by going to Window | General | Python Script Editor.
  2. Enter print ('Hello World from Python') in...

Further reading

You can learn more about gizmos at the following links:

  • The Unity Gizmos manual entry at https://docs.unity3d.com/ScriptReference/Gizmos.html
  • Unity Gizmos tutorial: https://learn.unity.com/tutorial/creating-custom-gizmos-for-development-2019-2

You can learn more about Unity testing at the following links:

Learn more on Discord

To join the Discord community for this book – where you can share feedback, ask questions to the author, and learn about new releases – follow the QR code below:

https://packt.link/unitydev

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Unity Cookbook - Fifth Edition
Published in: Nov 2023Publisher: PacktISBN-13: 9781805123026
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.
undefined
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 €14.99/month. Cancel anytime

Authors (3)

author image
Shaun Ferns

Shaun is a lecturer at Technological University Dublin. He is currently teaching on the BA (Hons) in Creative Digital Media where he is lead in the delivery of the Multimedia Stream. He is currently exploring serious games for construction-related training as well as the opportunities transmedia provides in improving user experience and engagement in cultural archive artifacts. His educational research is currently driven by his interest in self-determined learning (heutagogy), rhizomatic learning theory, micro-credentialing /digital badging, and curriculum development.
Read more about Shaun Ferns

author image
Sinéad Murphy

Sinead Murphy is currently Data Analytics Manager for the Irish NGO Trocaire. She has over 25 years of computing experience, including freelance IT training and database consulting, university lecturing in mathematics, IT skills and programming at TU Dublin (Ireland) and Middlesex University (London). She is a published academic, with undergraduate and postgraduate degrees in mathematics, computing and data science. She is passionate about the use of IT for understanding and visualising data, and using that understanding to make meaningful differences in the world. She is currently exploring the use of Python and Unity for data analytics and interactive visualisations.
Read more about Sinéad Murphy