8. Debugging

uke 的头像

Debugging is the skill of finding and fixing human errors in your code (ok let’s call them
mistakes!). Unity provides help via the Debug class, we’ll now look at the Debug.Log()
function.
Log
The Log() function allows the user to send a message to the Unity Console. Reasons for
doing this might include:
1. To prove that a certain part of the code is being reached during run-time.
2. To report the status of a variable.
We’ll now use the Log() function to send a message to the Unity Console when the user
clicks the fire button.
- Open the Create script and add the following line after the ‘Instantiate’ code inside the
‘if’ block:
Debug.Log("Cube created");
- Run the game and click the fire button, you should see a line appear at the bottom of
the Unity GUI saying “Cube created”, you can click on this to examine the Unity
Console.
Watch
Another useful feature for debugging is exposing a private variable. This makes the
variable visible in the Inspector View when the Debug mode is selected, but it cannot be
edited.
To demonstrate this, we’ll expose a private variable to count the number of cubes that we
instantiate.
- Open the Create script again and add two lines:
(1) Add a private variable called cubeCount
(2) Increment this variable whenever a cube is instantiated.
The complete code is a follows (Create.js):
var newObject : Transform;
private var cubeCount = 0;
function Update () {
if (Input.GetButtonDown("Fire1")) {
Instantiate(newObject, transform.position, transform.rotation);
Debug.Log("Cube created");
cubeCount++;
}
}
8
- Run the game and click the fire button to create some cubes. Notice in the Inspector
View how the cubeCount variable is incremented whenever a new cube is instantiated.
Notice also how the number appears greyed out, this denotes that it’s a read-only
variable (cannot be edited).