Code works for my player piece but not my ai - collisions

Hey guys,
I’m pretty new to Unity and I’m trying to create an Air Hockey game. If a player hits the puck twice before the other player does, they lose a point. This works for my player but not for the ai and I’m not sure why. I also tried to include a lower limit so the score never goes below 0, but that is not working either.

Here’s the code:

private void OnCollisionEnter2D(Collision2D collision)
    {
        audioManager.PlayPuckCollision();

        if (collision.gameObject.CompareTag("Player"))
        {
            HandleCollision("Player");
        }
        else if (collision.gameObject.CompareTag("AI"))
        {
            HandleCollision("AI");
        }
    }
   
    private void HandleCollision(string collidedWithTag)
    {
        if (LastHit != null && lastCollidedWithTag == collidedWithTag)
        {
            if (collidedWithTag == "Player" && Score.eScore.PlayerScore != 0)
                ScoreMinus.Decrement(Score.eScore.PlayerScore);
            else if (collidedWithTag == "AI" && Score.eScore.AIScore != 0)
            {
                Debug.Log("Decrease AI");
                ScoreMinus.Decrement(Score.eScore.AIScore);
            }
        }
        LastHit = gameObject;
        lastCollidedWithTag = collidedWithTag;
    }

And this is the function I’m calling from my Score Script:

public void Decrement(eScore MinusScore)
    {
        if (MinusScore == eScore.PlayerScore)
            PlayerScoreText.text = (--PlayerScore).ToString();
        else
            AIScoreText.text = (--AIScore).ToString();
    }

Any help would be appreciated!

1 Like

I would try testing it out using a duplicated player object tagged with “AI” to figure out whether the problem is do to with the code itself or the tags/colliders of your objects. It could be caused by a difference between the Ai and player.

2 Likes

It still doesn’t work with a duplicated player object tagged as AI. I’m not sure what to do from here because everything seems right to me

Start debugging!

By debugging you can find out exactly what your program is doing so you can fix it.

Use the above techniques to get the information you need in order to reason about what the problem is.

Once you understand what the problem is, you may begin to reason about a solution to the problem.