OnCollisionEnter2D error

Hi, I’m getting an error:
ArgumentOutOfRangeException: Index and length must refer to a location within the string.
Parameter name: length
System.String.Substring (System.Int32 startIndex, System.Int32 length) (at <890d6fe26e8c408ea64b353e791fafce>:0)
PlayerController.OnCollisionEnter2D (UnityEngine.Collision2D collision) (at Assets/Scripts/PlayerController.cs:139)

I have a GameObject named HouseCollider, which acts as a barrier. It has a rigidBody2D with static body type and a box collider 2D
and when it collides with the player it throws out this error.
The player has a polygon collider that detects collisions and a circle collider that acts as a trigger to pick up collectibles.

Here is the Collision code of the player:

//COLLISION
    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject != null)
        {
            GameObject collisionGameObject = collision.gameObject;
            if (collisionGameObject.name.Substring(0, 13) == "PickUpsHealth")
            {
                healthBar.value += healAmount * GlobalVariables.globalHealAmount;
                Destroy(collisionGameObject);
            }
            else if (collisionGameObject.name.Substring(0, 14) == "PickUpsBullets")
            {
                bulletCountBar.value += bulletAmount * GlobalVariables.globalAmmoAmount;
                Destroy(collisionGameObject);
            }
            else if (collisionGameObject.name.Substring(0, 13) == "PickUpsShells")
            {
                shellCountBar.value += shellAmount * GlobalVariables.globalAmmoAmount;
                Destroy(collisionGameObject);
            }
        }
    }

Collectible pick ups work without an issue, it’s just when it collides with the house that I get the error and I have no idea why.

You are querying the substring with a fixed length, e.g. 14. If the name of the object you collide with is shorter it will fail.
Using Strings isn’t best practice anyway. You should dig into the concept of Layers.

Nevermind I fixed it.

Added an exception for the HouseCollider in script and changed the order of collision checks based on gameObject.name length from shortest to longest. So that if I collide with something that has a shorter name it would check it first.

Thanks for the reply. I do have collectibles on a separate layer for collision detection, but I do need to distinguish them so I used the name for that.

I could make a separate layer for all of them?

There’s no need to check if Collision2D.gameObject is null or not. You cannot get a callback for something that doesn’t exist.