Coin Collector Game

I’ve build a 3D game with unity ver. 2019.4. The game is basically a obstacle avoiding car racing game to which I’ve added incentives in the form of candies which I want to disappear when ,y car touches them. I also want to display the number of candies I’ve collected in the overall game. I wrote the following code to do the same:

void OnTriggerEnter(Collider col)
    {
        if (col.gameObject.tag == "candy")
        {
            Destroy(col.gameObject);
            i++;
            Score.text = ":" + i;
        }
    }

For the first candy I encounter the code works well and the counter displays 1, but for the subsequent candies neither the counter increments nor the candies destroys. Am I missing something here?
Thanks for your time and help.

Check to make sure all your candy have the tag ‘candy’. If you’re using prefabs, make sure you’ve applied any changes.

I checked, all the tags are proper. Is there any other way to achieve the same?
Thanks

Where is ‘i’ defined? Seems to me that your statement will never increase past 1 if i is a local variable. You also didn’t mention what gameobject(s) your script is attached to.
One solution could be to not use tags on your candy and instead tag the car as a car and have each candy check for collision. If the collision occurs, a third script keeping track of score would be incremented by one.
Now, how you communicate between the candies and the point script is up to you: it’s possible to create a public reference on the candy script pointing to the point script, do a GameObject.Find and subsequently a GetComponent to access the script, creating a script instance, or creating a delegate and using events to trigger a point change. Hope this helps.

1 Like

This seems to be a good idea. I did make the ‘i’ a local variable, I think that’s where the problem lies. Thanks a lot for your help!