Search Unity

coin collecting script not working properly

Discussion in 'Scripting' started by prvy_plamen, Dec 1, 2015.

  1. prvy_plamen

    prvy_plamen

    Joined:
    Dec 1, 2015
    Posts:
    2
    I wrote this for Coin collecting in a 2d game I'm working on. Problem is that script isn't counting properly, it sometimes counts two coins instead of one. Scripts is attached to the player. Could you help me with that, I'm new in this, this is my second project in Unity ever. Thank you.


    using
    UnityEngine;
    using System.Collections;

    public class Coin : MonoBehaviour
    {
    public TextMesh coinCount;
    public AudioClip coinCollect;

    int CoinAmount;

    void Update()
    {
    coinCount.text = "" + CoinAmount;
    }

    void OnTriggerEnter(Collider collider)
    {
    if (collider.tag == "dinar")
    {
    AudioSource.PlayClipAtPoint(coinCollect, transform.position);
    CoinAmount += 1;
    Destroy(collider.gameObject);
    }
    }
    }
     

    Attached Files:

    • Coin.cs
      File size:
      528 bytes
      Views:
      755
  2. Ian094

    Ian094

    Joined:
    Jun 20, 2013
    Posts:
    1,548
    You should use :
    Code (CSharp):
    1. OnTriggerEnter2D(Collider2D col){
    2. ...
    3. }
    For 2D games.

    Check that you don't have multiple Colliders on your player cus that can cause OnTriggerEnter being called multiple times.
     
    prvy_plamen likes this.
  3. prvy_plamen

    prvy_plamen

    Joined:
    Dec 1, 2015
    Posts:
    2
    thanks, there were multiple colliders, it works fine now.