Game Development Reference
In-Depth Information
When an error occurs during runtime, Unity creates an
exception
object, then
throws
the exception.
The exception must be
caught
and dealt with for execution of the script to proceed. If your script
doesn't provide a means to handle the exception properly, a default handler catches the exception
and generates the error message. Depending on the error, it may even
crash
, or terminate the game.
In this example, since the error occurs in the code block for calculating the explosive force on
the boxes around the player character when he lands, when this error is thrown the boxes remain
stacked neatly because the explosion force could not be properly calculated or applied.
Looking again at Figure
10-20
, you can see that two error messages were generated: one for the
mathematical error of dividing by zero, followed by the subsequent inability to calculate the Vector3
coordinates of the argument used in
AddExplosionForce()
. By addressing the first error listed in the
Console first, when you fix the divide-by-zero bug, the second related error will also be resolved.
Remove the error, save the script, and playtest, and your scene is up and running error-free again.
You can also create your own error messages using
Debug.LogError
. Add the following line of code
as the first line of the
ImpactForce()
function:
Debug.LogError("My test error message", gameObject);
Save the script and playtest. The error message complete with red icon appears in the Console as
expected. While the error message you created appears to act the same as a LogWarning message
other than the icon,
Debug.LogError
also works in conjunction with the Unity debugger to help you
follow the execution of your script step by step at runtime. While using the Unity debugger is a more
advanced topic, for future reference be aware that there are more complex uses of the Debug class
you will eventually find useful.
Exception Handling
You have already written code that helps to prevent throwing exceptions. Look again at the
OnCollisionEnter()
function of the KillOnCollision script:
function OnCollisionEnter(other : Collision) {
if (other.gameObject.name == "Third Person Character Ragdoll")
{
other.gameObject.GetComponent(GoRagdoll).GotoRagdoll();
}
}
The conditional checks to make sure the game object involved in the collision is the player character
before accessing and calling the
GotoRagdoll()
function on its GoRagdoll script component.
Suppose that you didn't check and wrote the function simply as:
function OnCollisionEnter(other : Collision) {
other.gameObject.GetComponent(GoRagdoll).GotoRagdoll();
}
This might have made sense when the only moving game object was the player character. But as
you continued to build the obstacle course, you added other moving objects—the enemy drones.
If the player were to retreat along the obstacle course to escape the drone, and the following drone