1
votes

I am creating a basic game for test purpose in unity3D where i will counter the number of objects whenever the collision occurs on the defined object. I have created objects named birds1 upto birds8 While hitting the objects with name birds1, birds2. I am trying to increment the counter, it should increment the value of f by 1, if the hit the bird here the counter increments by random number instead of increment by 1. I have set a value that the counter should not exceed a limit of 8 so it stops at a limit of 8. Below is my code i am posting the code that i am using. Please can anyone help me with this that where is my code running wrong.

public void OnTriggerEnter2D(Collider2D target)
    {
        if (target.gameObject.name == "bird1" || target.gameObject.name == "bird2" || target.gameObject.name == "bird3" || target.gameObject.name == "bird4" || target.gameObject.name == "bird5" || target.gameObject.name == "bird6" || target.gameObject.name == "bird7" || target.gameObject.name == "bird8" && f < 8)
        {
            f++;
            propPAnel8.SetActive(true);
            BirdText.text = "x " + f;
            if (f == 8)
            {
                bound8.isTrigger = true;
            }
        }
    }
1
Can you show the collision code that envelopes this if-statement? There doesn't seem to be anything wrong with this code. Just FYI you can assign a "tag" to every type of bird and just do if (target.gameObject.tag == "bird") instead of checking for each individual bird name. - ryeMoss
@ryeMoss I have updated the code - MAyank Jajam
@ryeMoss i have also tried to tag all the birds in same tag but it still give random increment. - MAyank Jajam
does birds have only one collider. - deepankar
@SerkanPekçetin thanks,that worked for me. - MAyank Jajam

1 Answers

0
votes

OnTriggerEnter2D will be called multiple times, especially if you have colliders with multiple contact points: That is why the increment in f it appears seemingly random, however, in this case, it is not.

You get increments as much as your contact points during the collision. What are you trying to achieve with the increment of 1? Maybe you need a boolean instead and setting isTrigger property of your Collider2D to false would help, but that depends on your game logic.