Most probably you already know about Debug.Log() function and its variations, but did you know that you can use it to find a particular object on the scene?
Why would you do that? For instance, let’s say that you’re creating a shooting game. When a player shoots the object, you want to check if the bullet hits the right one. How can you do that?
Debug.Log() function can have one or two parameters:
The first one is a message. It can be a string or an object that will be converted to a string. The second one is a context. As a context you should pass the object that current message applies to. In our case, this would be the target hit of the bullet.
Example
Let’s take a look at this example:
using UnityEngine;
public class Target : MonoBehaviour {
public void Update() {
// waiting for a mouse click
if (Input.GetMouseButtonDown(0)) {
// raytracing the click
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit)) {
// hit current object?
if (hit.collider.gameObject == gameObject) {
// hit!
Debug.Log("Hit!", this);
}
}
}
}
}
In this example we wait for a mouse click (7), then do a ray-cast from the camera position (12), check if hit object is the current game object (15) and finally display the “Hit!” log message (18). By passing this as the second parameter, the log entry is aware of its creator and we are able to easily trace it back.
See that yellow highlighting animation around the object name in the Hierarchy? In that way the Unity tells you that this object is the creator.
You may ask: why not simply log object name like Debug.Log(name);? The answer is really simple. If you generate scene objects, most probably all of them are called the same. This is perfectly legal (normal?) for Unity to have multiple hierarchy objects with the same name, so Debug.Log() with context parameter comes to the rescue!
Files
If you’d like to check it by yourself, you can download the unitypackage file, then double-click on it to import its content into your Unity project. You will find there an example scene and a script from above.