Console log can show you which object is the creator

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:

debug log definition

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.


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!


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.

Executing Custom Scripts from Unity’s Menu
You can do wonderful things with your Unity editor via scripting. For instance, you can write...
Wrong Import Settings are Killing Your Unity Game [Part 1]
There are many things that may go wrong with your game development. Your models may have too...
MonoBehavior calls optimization
What if I told you that Unity can be wasting a lot of CPU performance just by calling your...
Call The Knights!
We are here for you.
Please contact us with regards to a Unity project below.

The Knights appreciate your decision!
Expect the first news soon!
hire us!