Zayd Carelse Zayd Carelse is a Unity-certified developer for a studio focused on VR and AR as a medium and runs an indie game studio called Brain Drain Games. He loves to travel, can speak both Mandarin and Vietnamese, and is obsessed with anything related to The Elder Scrolls.

Optimizing your Unity project with Debug.Log

6 min read 1778

Unity Logo

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.


More great articles from LogRocket:


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.

: Full visibility into your web and mobile apps

LogRocket is a frontend application monitoring solution that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.

In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single-page and mobile apps.

.
Zayd Carelse Zayd Carelse is a Unity-certified developer for a studio focused on VR and AR as a medium and runs an indie game studio called Brain Drain Games. He loves to travel, can speak both Mandarin and Vietnamese, and is obsessed with anything related to The Elder Scrolls.

Leave a Reply