Problem with Collision Detection Counting in Unity (C#)

I’m experiencing an issue with my Unity game where a collision count is being incremented at the start of the game, even though no collisions have occurred. Here is the relevant script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Scorer : MonoBehaviour
{
int hits = 0;

private void OnCollisionEnter(Collision other)
{
    hits += 1;
    Debug.Log("You've bumped into a thing this many times: " + hits);
}

}

When the game starts, I get the message “You’ve bumped into a thing this many times: 1” even though the player hasn’t collided with anything. How can I prevent this initial collision count and ensure the counter only increments when actual collisions happen during gameplay?

If your plane has a collider, it will register a hit at the start. Put the plane on a ground layer and exclude it from the counter script.

Hi Shrikant,

edc237 is right. At the moment, we do not filter for anything, so each collision increments the hits.

To add restrictions, we need if-statements, which are taught in one of the next videos. Please keep watching. :slight_smile:


See also:

Thank You Very Much For your Help , And i understand what mistake i am doing

Thank You So Much Again

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

You didn’t make any mistake. What you experienced in your game is the correct behaviour. The physics simulation is optimised for speed, not precision. Placing a collider directly on another collider is not a reliable solution. In Rick’s case, it worked but that’s more or less a coincidence. The only reliable solution is an if-statement that ensures that we increment hits only in a specific situation. :slight_smile:

Privacy & Terms