0
votes

(Probably pepole are gonna complain that I'm stupid or whatever but anyways)

Hi, I have a problem regarding the OnCollisionExit2D function in Unity. I am making a 2D city-building style game and I started making electricity system for the buildings. It works like this: If there are no power plants nearby (they have radius colliders) then the electricityNeed bool on building within the radius turns true, when the power plant is destroyed/building not being in the radius, it should set it to false. For doing this I'm using the OnCollisionEnter2D (which works perfectly) and a OnCollisionExit2D. Below is the code responsible for switching the electricityNeed bool (It's in the building script).

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if(collision.gameObject.tag.Equals("Electricity"))
        {
            electricityNeed = true;
        }
    }

    private void OnCollisionExit2D(Collision2D collision)
    {
        if(collision.gameObject.tag.Equals("Electricity"))
        {
            electricityNeed = false;
            Debug.Log("It should set electricityNeed to false.");
        }
    }

When the building is withing the range of a power plant it turns to true, but when the power plant dissappears, the bool is still true.

Both building and the power plant have a Non Kinematic rigidbody2D and a collider (power plant have a Circle2D one and the building has a Box2D collider.)

The power plant has the tag "Electricity" and i checked it multiple times.

If you want to help me but the info i sent here is not enough, then please inform me about it.

Thanks in advance.

1
In general rather use if(collision.gameObject.CompareTag("Electricity")) to avoid silent fails in case of typosderHugo
Thanks for the advice : ), sadly that didn't fix the problem.GraczBezNicku

1 Answers

1
votes

For some reason deleting an object from hierarchy is not considered OnCollisionExit2D. When I fixed the problem with deleting the power plant building (The radius was considered an occupied building place) it suddenly works. I did it by creating a child object with a colider with tag "radius" which the Collision Detection needs to ignore when placing/deleting.

    private void OnCollisionEnter2D(Collision2D collision)
    {
        colidingBuilding = collision.gameObject;
        if (colidingBuilding.tag.Equals("Radius"))
            return;
        isColliding = true;
    }

If anyone experiences problem like this just try my answer.