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 2017 Mobile Game Development

You're reading from   Unity 2017 Mobile Game Development Build, deploy, and monetize games for Android and iOS with Unity

Arrow left icon
Product type Paperback
Published in Nov 2017
Publisher Packt
ISBN-13 9781787288713
Length 360 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
John P. Doran John P. Doran
Author Profile Icon John P. Doran
John P. Doran
Arrow right icon
View More author details
Toc

Table of Contents (11) Chapters Close

Preface 1. Building Your Game FREE CHAPTER 2. Setup for Android and iOS Development 3. Mobile Input/Touch Controls 4. Resolution Independent UI 5. Advertising Using Unity Ads 6. Implementing In-App Purchases 7. Getting Social 8. Using Unity Analytics 9. Making Your Title Juicy 10. Game Build and Submission

Improving our scripts with attributes and XML comments

We could stop working with the PlayerBehaviour class script here, but I want to touch on a couple of things that we can use in order to improve the quality and style of our code. This becomes especially useful when you start building projects in teams, as you'll be working with other people--some of them will be working on code with you, and then there are designers and artists who will not be working on code with you, but will still need to use the things that you've programmed.

When writing scripts, we want them to be as error-proof as possible. Making the rb variable private starts that process, as now the user will not be able to modify that anywhere outside of this class. We want our teammates to modify dodgeSpeed and rollSpeed, but we may want to give them some advice as to what it is and/or how it will be used. To do this in the Inspector window, we can make use of something called an attribute.

Using attributes

Attributes are things we can add to the beginning of a variable, class, or function declaration, which allow us to attach an additional functionality to them. There are many of them that exist inside Unity, and you can write your very own as well, but, right now, we'll talk about the ones that I use most often.

The Tooltip attribute

If you've used Unity for a period of time, you may have noted that some components in the Inspector window, such as the Rigidbody, have a nice feature--if you move your mouse over a variable name, you'll see a description of what the variables are and/or how to use them. The first thing you'll learn is how we can get the same effect in our own components by making use of the Tooltip attribute. If we do this for the dodgeSpeed and rollSpeed variables, it will look something like this:

[Tooltip("How fast the ball moves left/right")] 
public float dodgeSpeed = 5;

[Tooltip("How fast the ball moves forwards automatically")]
public float rollSpeed = 5;

Save the preceding script and return to the editor:

Now, when we highlight the variable using the mouse and leave it there, the text we placed will be displayed. This is a great habit to get into, as your teammates can always tell what it is that your variables are being used for.

For more information on the Tooltip attribute, check out, https://docs.unity3d.com/ScriptReference/TooltipAttribute.html.

The Range attribute

Another thing that we can use to protect our code is the Range attribute. This will allow us to specify a minimum and maximum value for a variable. Since we want the player to always be moving forward, we may want to restrict the player from moving backward. To do that, we can add the following highlighted line of code:

    [Tooltip("How fast the ball moves forwards automatically")] 
[Range(0, 10)]
public float rollSpeed = 5;

Save your script, and return to the editor:

We have now added a slider beside our value, and we can drag it to adjust between our minimum and maximum values. Not only does this protect our variable, it also makes it so our designers can tweak things easily by just dragging them around.

The RequireComponent attribute

Currently, we are using the Rigidbody component in order to create our script. When working as a team member, others may not be reading your scripts, but are still expected to use them when creating gameplay. Unfortunately, this means that they may do things that have unintended results, such as removing the Rigidbody component, which will cause errors when our script is run. Thankfully, we also have the RequireComponent attribute, which we can use to fix this.

It looks something like this:

using UnityEngine; 

[RequireComponent(typeof(Rigidbody))]
public class PlayerBehaviour : MonoBehaviour

By adding this attribute, we state that when we add this component to a game object and it doesn't have a Rigidbody attached to its game object, the component will be added automatically. It also makes it so that if we were to try to remove the Rigidbody from this object, the editor will warn us that we can't, unless we remove the PlayerBehaviour component first. Note that this works for any class extended from MonoBehaviour; just replace Rigidbody with whatever it is that you wish to keep.

Now, if we go into the Unity editor and try to remove the Rigidbody component by right-clicking on it in the Inspector and selecting Remove Component, the following message will be seen:

This is exactly what we want, and this ensures that the component will be there, allowing us not to have to include if-checks every time we want to use a component.

XML comments

Note that previously we did not use a Tooltip attribute on the private rb variable. Since it's not being displayed in the editor, it's not really needed. However, there is a way that we can enhance that as well, making use of XML comments. XML comments have a couple of nice things that we get when using them instead of traditional comments, which we were using previously. When using the variables/functions instead of code in Visual Studio, we will now see a comment about it. This will help other coders on your team have additional information and details to ensure that they are using your code correctly.

XML comments look something like this:

/// <summary> 
/// A reference to the Rigidbody component
/// </summary>
private Rigidbody rb;

It may appear to be a lot more writing is needed to use this format, but I did not actually type the entire thing out. XML comments are a fairly standard C# feature, so if you are using MonoDevelop or Visual Studio and type ///, it will automatically generate the summary blocks for you (and the param tags needed, if there are parameters needed for something like a function).

Now, why would we want to do this? Well, now, if you select the variable in Intellisense, it will display the following information to us:

This is a great help for when other people are trying to use your code and it is how Unity's staff write their code. We can also extend this to functions and classes to ensure that our code is more self-documented.

Unfortunately, XML comments do not show up in the Inspector, and the Tooltip attribute doesn't show info in the editor. With that in mind, I used Tooltips for public instructions and/or things that will show up in the Inspector window, and XML comments for everything else.

If you're interested in looking into XML comments more, feel free to check out: https://msdn.microsoft.com/en-us/library/b2s063f7.aspx.

Putting it all together

With all of the stuff we've been talking about, we can now have the final version of the script, which looks like the following:

using UnityEngine; 

/// <summary>
/// Responsible for moving the player automatically and
/// reciving input.
/// </summary>
[RequireComponent(typeof(Rigidbody))]

public class PlayerBehaviour : MonoBehaviour
{
/// <summary>
/// A reference to the Rigidbody component
/// </summary>
private Rigidbody rb;

[Tooltip("How fast the ball moves left/right")]
public float dodgeSpeed = 5;


[Tooltip("How fast the ball moves forwards automatically")]
[Range(0, 10)]
public float rollSpeed = 5;

/// <summary>
/// Use this for initialization
/// </summary>
void Start ()
{
// Get access to our Rigidbody component
rb = GetComponent<Rigidbody>();
}

/// <summary>
/// Update is called once per frame
/// </summary>
void Update ()
{
// Check if we're moving to the side
var horizontalSpeed = Input.GetAxis("Horizontal") *
dodgeSpeed;

// Apply our auto-moving and movement forces
rb.AddForce(horizontalSpeed, 0, rollSpeed);
}
}

I hope that you also agree that this makes the code easier to understand and better to work with.

You have been reading a chapter from
Unity 2017 Mobile Game Development
Published in: Nov 2017
Publisher: Packt
ISBN-13: 9781787288713
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