Home > Software design >  Colliding in C# (Unity)
Colliding in C# (Unity)

Time:05-05

I'm pretty new to C# and i'm currently developing a small 2D game. I have a Skript for the Collisions, so that i get a Debug.log() whenever my character touches something. That is the Skript:

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

public class Collidable : MonoBehaviour
{
    public ContactFilter2D filter;
    private BoxCollider2D boxCollider;
    private Collider2D[] hits = new Collider2D[10];

    protected virtual void Start()
    {
        boxCollider = GetComponent<BoxCollider2D>();
    }

    protected virtual void Update()
    {
        //Collision Work
        boxCollider.OverlapCollider(filter, hits);
        for(int i=0; i<hits.Length; i  )
        {
            if(hits[i] == null)
                continue;
          
            OnCollide(hits[i]);


            hits[i] = null;
        }
    }
    protected virtual void OnCollide(Collider2D coll)
    {
        Debug.Log(coll.name);
    }
}

I would like to get only 1 console log whenever my character is, for example, picking up, therefore, touching a chest and get a message what he picked up, but for as long as the character is touching the chest, the Logs won't stop flying. How can i fix that?

Thanks in advance

CodePudding user response:

You have to add a flag (a boolean) to call the method only once

At the top of the script, initialize a boolean variable hasCollided which is set to false on default.

private bool hasCollided = false;

Call the OnCollide() method only when the collision has not occurred yet and when the collision has occurred, set hasCollided to true.

protected virtual void OnCollide(Collider2D coll)
{
    if(!hasCollided)
    {
        Debug.Log(coll.name);
        hasCollided = true;
    }
}

This calls the OnCollide() method only once.

CodePudding user response:

The official documentation for Collider2D.OverlapCollider states that

Get a list of all colliders that overlap this collider.

and you are checking that on Update() meaning your collision code get executed everytime there are any collider overlapping your BoxCollider2D

You should look into Collider.OnCollisionEnter which gets called when this collider/rigidbody has begun touching another rigidbody/collider.

However collision events are only sent if one of the colliders also has a non-kinematic rigidbody attached.

  • Related