CodeBlanks Logo Icon CodeBlanks

Challenge 4: Collision log

Write a C# script that reports collisions with OnCollisionEnter.

Challenge 4: Collision report

In the physics engine, when two solid Colliders make contact, the OnCollisionEnter callback fires. This method delivers colliding object name, contact points, and velocity data via the Collision parameter.

void OnCollisionEnter(Collision collision) {
    Debug.Log("Collided with: " + collision.gameObject.name);
}

Enemy impacts, bullet strikes, or wall collisions trigger their respective gameplay feedback routines inside this function.

Practice Print collided obstacle

Assign "Obstacle" to the obstacle variable and print Collision: Obstacle to the console.

Starter code

Player.cs
using System;

class Program
{
    static void Main()
    {
        // obstacle değişkenini tanımlayıp çarpışmayı yazdır
    }
}

Sample solution

Player.cs
using System;

class Program
{
    static void Main()
    {
        string obstacle = "Obstacle";
        Console.WriteLine("Collision: " + obstacle);
    }
}

Expected output

Collision: Obstacle

Practice Print target and obstacle type

Assign "Spike" to target and "Hazard" to type. Print Hit: Spike | Type: Hazard to the console.

Starter code

Player.cs
using System;

class Program
{
    static void Main()
    {
        // target ve type değerlerini tanımlayıp yazdır
    }
}

Sample solution

Player.cs
using System;

class Program
{
    static void Main()
    {
        string target = "Spike";
        string type = "Hazard";
        Console.WriteLine("Hit: " + target + " | Type: " + type);
    }
}

Expected output

Hit: Spike | Type: Hazard

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What type of information is contained inside the Collision parameter passed by Unity into OnCollisionEnter?

  • The collided object, contact points, and impact velocity Correct answer
  • Only the instantaneous temperature and memory of the GPU
  • The aggregate playback duration of all project audio files
  • Only the current frames-per-second (FPS) count of the game

Explanation: The Collision object encapsulates comprehensive physics data including hit GameObject, surfaces, and impact velocities.

2 Specify collision parameter type

Question
void OnCollisionEnter(____ collision)
Answer
void OnCollisionEnter(Collision collision)

Explanation: The OnCollisionEnter method accepts collision data as a parameter of type Collision.

3 Collision report elements

Term Meaning
OnCollisionEnter Physics method on first object contact
Collision Holds contact & colliding object data
gameObject.name Name shown in Hierarchy panel
Debug.Log Logs collision notification to console

All lessons in Beginner