This is a premium alert message you can set from Layout! Get Now!

Optimizing your Unity project with Debug.Log

0

So you want to build a game using the Unity engine? You’ve sat down and designed the game that you’d like to create, put together a little project management board, and you’ve started implementing the logic needed to drive your game.

You’ve hit the Play button a few times and tested a few of the scripts that you’ve created for the base functionality and now that you’re working on something a little more complex, you’ve hit Play and your IDE (Integrated Development Environment) hasn’t thrown any errors your way.

My Code Works But How Gandalf Meme

Everything looks good and the game runs, but something isn’t quite right. You’re not getting the data that you’re expecting to get or you’re just not getting the results that you need. This can be super frustrating as a Unity beginner, but this article will help you get through the process of debugging your Unity project using the Debug.Log statement.

We’ll be running through the different ways that you can use the Debug.Log statement, formatting the output to be more readable and looking at a few ways to ensure that you’re using the Debug.Log statement effectively.

For this article, I’ll be assuming that you’re familiar with the Unity engine interface and have already written your first script. We’ll be creating a very simple project with which to demonstrate the use of the statements, but I’ll be adding screenshots and an explanation of the process as we go along.

Setting up the base project

For this article, I’ll be creating a 3D project in Unity 2021.3.4f1, but the version of the Unity engine that you use will not matter. I’ll also be using VS Community 2019, so you may notice a few interface differences if you’re using VS Code or the Rider IDE, but the principles demonstrated here will be applicable to any IDE.

In the scene below, I’ve got a plane and a few primitive objects. Each of these objects has a unique name (their primitive type), transform, and script. They will be numbered 1 (Sphere), 2 (Cube), 3 (Capsule), and 4 (Cylinder), respectively.

Objects With Names

Next, I created a folder for my scripts, a GameManager script and a GameManager game object within the Hierarchy which will contain the GameManager script that I’ve just created.

GameManager Script Object

I then dragged or assigned the GameManager.cs script to the game object that I created in the Hierarchy, which will run when we hit the play button. Now that we’re all set up, we can look at the basic usage of the Debug.Log statement.

Script to Game Object

How to use the Debug.Log statement in Unity

Now that we have our GameManager script assigned to the GameManager game object within our Test Scene, we can insert our first Debug.Log statement to test that it runs when we need it to.

The syntax for the Debug.Log statement is as seen in the screen to the right. Here I’ve simply stated “Debug.Log(”Hello!);” and since I’ve inserted this statement into our Start method, this should run once when we run our game:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GameManager : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        Debug.Log("Hello!");
    }

    // Update is called once per frame
    void Update()
    {

    }
}

If we go ahead and hit the Play button in the Unity Editor, you’ll see word “Hello!” printed in the Editor Console window.

Hello World Unity Editor

We are now able to output simple text to the console using the Debug.Log statement, but it’s still not really that valuable to us when debugging. So let’s try displaying the value of a certain variable that we’ve created when we start up our game.

To do this, I’ve created a private integer called testValue (as seen below) within our GameManager.cs script and I’ve assigned a value to it within the Start function. You may also note that I am able to create a more complex Debug.Log statement by combining the text and the testValue and separating it with a + sign. You’ll also notice that I’ve added a space character between the last character of the simple text and the variable to create some space in the Console window:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GameManager : MonoBehaviour
{
    private int testValue;

    // Start is called before the first frame update
    void Start()
    {
        testValue = 1000;
        Debug.Log("This is the value of testValue: " + testValue);
    }

    // Update is called once per frame
    void Update()
    {

    }
}

Let’s save our script and head back to the Unity editor to see what the output in the console will be.

TestValue 1000

Great! We can now see the assigned value of testValue, as well as the little bit of text we’ve added for us to better understand the output in the Console window.

Using the Debug.Log statement to determine the name of a game object

Let’s create a reference to a game object within our script, attach it to the script within the Unity Editor, and then use the Debug.Log statement to output the name of that object:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GameManager : MonoBehaviour
{
    public GameObject testObject;

    void Awake()
    {
        Debug.Log(testObject.name);
    }
}

Once you’ve attached the object to the game object field on the GameManager.cs script, within the Unity Editor, you’ll be able to hit Play and the name of the game object that’s being referenced will be shown in the editor.

Name of Object Shown

Using the Debug.Log statement to determine the value of a conditional

We could also use the Debug.Log statement to determine the value of a conditional or a Boolean. Let’s create two integer values and then check whether or not they are the same. To do this, I’ve declared and initialized two integers (a and b) and used a Debug.Log statement to check if they are equal:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GameManager : MonoBehaviour
{
    private int a = 51;
    private int b = 62;

    void Awake()
    {
        Debug.Log(a == b);
    }
}

Since the a is not the same as b, the output of the console is as expected.

False Message

Using the Debug.Log statement to determine when a function is being called

In the previous section, we learned about the syntax for a simple Debug.Log statement and added a variable value to the statement. We were also able to see the output to the console. In this section, I’ll be looking at the timing of certain Unity functions and how to tell when a custom function has been called.

The following is taken from the official Unity documentation on the order of execution for event functions.

Unity script functions will execute in a defined order when your script is run and it can be really valuable to see when a specific event or function is triggered, when debugging. Let’s have a look at the following flow diagram, provided by Unity.

From the diagram below, we can see that the Awake function is the first function to be called when a Unity script is run. We then have the OnEnable and Start methods running sequentially.

Diagram Showing Functions

Let’s test this order with a simple script and the insertion of a few Debug.Log statements. I’ve added a testValue integer and then customized each Debug.Log statement so that we know where each of them is being run. The statement above each Debug.Log statement simply increments the value of testValue:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GameManager : MonoBehaviour
{
    private int testValue = 0;

    private void Awake()
    {
        testValue++;
        Debug.Log("This was run in the Awake method: " + testValue);
    }

    private void OnEnable()
    {
        testValue++;
        Debug.Log("This was run in the OnEnable method: " + testValue);
    }

    private void Start()
    {
        testValue++;
        Debug.Log("This was run in the Start method: " + testValue);
    }
}

Let’s see what happens in the Console window when we hit the Play button.

Great! We can see that the Awake method executes first, the OnEnable method next and then the Start method. We can also see that each of these methods only runs once when we hit the Play button.

Three Messages

Now let’s create a custom function called OurOwnFunction, which will contain a Debug.Log statement of its own. We’ll call this function in two of the other Unity functions and see what the output is:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GameManager : MonoBehaviour
{
    private int testValue = 0;

    private void Awake()
    {
        testValue++;
        Debug.Log("This was run in the Awake method: " + testValue);
        OurOwnFunction();
    }

    private void OnEnable()
    {
        testValue++;
        Debug.Log("This was run in the OnEnable method: " + testValue);
    }

    private void Start()
    {
        testValue++;
        Debug.Log("This was run in the Start method: " + testValue);
        OurOwnFunction();
    }

    private void OurOwnFunction()
    {
        Debug.Log("This is the custom function call!");
    }
}

The output in the Console is shown below and we can now see that our custom function is called in the Awake and Start functions, respectively.

Five Messages

Other types of debug messages

Now, we’ve looked at ways in which we can use the Debug.Log statement, but there are also other categories of debug statements that we could use. These statements are used in the same way that the Debug.Log statement is used but allow us to display warnings or errors in the Unity Console:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GameManager : MonoBehaviour
{
    void Start()
    {
        Debug.Log("This is a normal log.");
        Debug.LogWarning("This is a warning message.");
        Debug.LogError("This is an error message.");
    }
}

And here we have the output of the above.

Output Messages

In conclusion

Using the Debug statement can be very helpful in seeing what the value of certain variables or objects are at runtime, determining whether or not a function is actually running how and when you mean it to or even just tracking down a pesky bug.

I hope that you have found this useful and are able to use Debug statements more effectively within your project. Just remember to remove them or turn them into comments when they’re no longer in use and you’re all set to debug your way out of your next big game.

The post Optimizing your Unity project with <code>Debug.Log</code> appeared first on LogRocket Blog.



from LogRocket Blog https://ift.tt/hcGizrX
Gain $200 in a week
via Read more

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Post a Comment

Search This Blog

To Top