Problem with score count

In my game I have the player collect coins. The coins have a value of one and are being picked up with on trigger enter. For some reason, when the player triggers the coin it it being doubled in value, so when the player collects one coin the coin counter goes to two, collect a second coin counter goes to four etc. Other weird thing is, the default start value is zero but when the game starts the coin value is blank instead of it displaying zero. I use the following two scripts, and as far as I can tell this should be correct, so not sure why this is happening. Anyone any ideas?
This is the player script I use to check ontrigger enter:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour

{
    private Rigidbody playerRb;
    private GameObject wing;
    private SkinnedMeshRenderer wingMesh;
    private AudioSource playerSound;
    private GameManager gameManager;
    public AudioClip jumpSfx;
    public AudioClip coinSfx;
    public AudioClip powerupLifeSx;
    private Animator anim;
    public float speed = 30.0f;
    public float jumpForce = 22.0f;
    public float flyForce = 8.0f;
    public float fallMultiplier = 3.0f;
    public float moveGravity = 1.0f;
    public float rotationSpeed = 720f;
    public int coin;
    public bool isOnGround;
    public bool canFly = false;
    private float ownX = 1.5f;
    private float ownY = 1.5f;
    private float ownZ = 1.5f;
    private Vector3 ownScale;


    void Start()
    {
        playerRb = GetComponent<Rigidbody>();
        playerSound = GetComponent<AudioSource>();
        anim = GetComponent<Animator>();
        wing = GameObject.Find("Wing00");
        wingMesh = wing.GetComponent<SkinnedMeshRenderer>();
        gameManager = GameObject.Find("GameManager").GetComponent<GameManager>();


        ownX = ownX / transform.parent.lossyScale.x;
        ownY = ownY / transform.parent.lossyScale.y;
        ownZ = ownZ / transform.parent.lossyScale.z;
    }

    void FixedUpdate()
    {
        PlayerMovement();
        SetOwnScale();
        SetAnimation();
        SetJumpVelocity();
    }

    void PlayerMovement()
    {
        float horizontalInput = Input.GetAxis("Horizontal");
        Vector3 movementDirection = new Vector3(horizontalInput, 0, 0);
        playerRb.AddForce(Vector3.right * horizontalInput * speed);
        //playerRb.AddForce(Physics.gravity * moveGravity);


        if (movementDirection != Vector3.zero)
        {
            Quaternion toRotation = Quaternion.LookRotation(movementDirection, Vector3.up);
            transform.rotation = Quaternion.RotateTowards(transform.rotation, toRotation, rotationSpeed * Time.deltaTime);
            if (playerRb.velocity.x > 8)
            {
                anim.SetBool("Run", true);
            }
            else
            {
                anim.SetBool("Run", false);
            }
        }
        if (Input.GetKeyDown(KeyCode.Space) && isOnGround)
        {
            {
                playerRb.AddForce(transform.up * jumpForce, ForceMode.Impulse);
                isOnGround = false;
                playerSound.PlayOneShot(jumpSfx);
                anim.SetBool("Jump", true);
            }
        }
        else if (Input.GetKeyDown(KeyCode.Space) && canFly)
        {
            playerRb.AddForce(transform.up * flyForce, ForceMode.Impulse);
            anim.SetBool("Flying", true);
        }
     
    }

    void SetJumpVelocity()
    {
        if (playerRb.velocity.y > 0.0f)
        {
            playerRb.velocity += Vector3.up * Physics.gravity.y * fallMultiplier * Time.deltaTime;
        }
    }

    void SetOwnScale()
    {
        ownScale = new Vector3(ownX, ownY, ownZ);
        transform.localScale = ownScale;
    }

    void SetAnimation()
    {
  

        if (playerRb.velocity.x > 8)
        {
            anim.SetBool("Run", true);
        }
        else
        {
            anim.SetBool("Run", false);
        }
    }


    void OnCollisionEnter(Collision other)
    {
        if (other.gameObject.CompareTag("Ground"))
        {
            isOnGround = true;
            playerRb.velocity = Vector3.zero;
            anim.SetBool("Jump", false);
        }

        if (other.gameObject.CompareTag("mPlatform_00"))
        {
            isOnGround = true;
            //playerRb.velocity = Vector3.zero;
        }
    }

    private void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("Coin"))
        {
            playerSound.PlayOneShot(coinSfx);
            Destroy(other.gameObject);
            gameManager.UpdateCoins(coin);
        }

        if (other.CompareTag("HealthPowerup"))
        {
            playerSound.PlayOneShot(powerupLifeSx);
            Destroy(other.gameObject);
        }

        if (other.CompareTag("WingPowerup"))
        {
            playerSound.PlayOneShot(powerupLifeSx);
            wingMesh.enabled = true;
            canFly = true;
         
            Destroy(other.gameObject);
            StartCoroutine(WingCountdown());
        }
    }

    IEnumerator WingCountdown()
    {
        yield return new WaitForSeconds(5.0f);
        wingMesh.enabled = false;
        canFly = false;
        anim.SetBool("Flying", false);
    }
}

Coin collection at line 140.
I had the gameManager.UpdateCoins(coin); part before the destroy first, I put it like this to see if that made any difference but result is the same.
This is the GameManager script that keeps track of the score:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class GameManager : MonoBehaviour
{
    public TextMeshProUGUI livesText;
    public TextMeshProUGUI coinsText;
    public int coins;
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
       
    }
    public void UpdateCoins(int addCoins)
    {
        coins += addCoins;
        coinsText.text = "Coins: " + coins;
    }
}

In the inspector I have the coin vallue in the PlayerController script set to 1

Add debug.logs to the Update Coins method and see the trace stack.
And check if there are no 2 colliders on the coins maybe

Yes, this… lots and lots of this.

You must find a way 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.

What is often happening in these cases is one of the following:

  • the code you think is executing is not actually executing at all
  • the code is executing far EARLIER or LATER than you think
  • the code is executing far LESS OFTEN than you think
  • the code is executing far MORE OFTEN than you think
  • the code is executing on another GameObject than you think it is
  • you’re getting an error or warning and you haven’t noticed it in the console window

To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run? what order does it run in?
  • what are the values of the variables involved? Are they initialized? Are the values reasonable?
  • are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

Knowing this information will help you reason about the behavior you are seeing.

You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as Debug.Log("Problem!",this);

If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

You could also just display various important quantities in UI Text elements to watch them change as you play the game.

If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer or iOS: https://discussions.unity.com/t/700551 or this answer for Android: https://discussions.unity.com/t/699654

Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

Here’s an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

https://discussions.unity.com/t/839300/3

When in doubt, print it out!™

Note: the print() function is an alias for Debug.Log() provided by the MonoBehaviour class.

Thanks for both responsen, debu.log solved it. On the player I had two box colliders. It is an asset store prefab and aparently a child element already had a box collider I didn’t know about, so I added my own boxcollider to the parrent. And the coin had a sphere collider with a trigger. I disabled the boxcollider on the child object. Im only sure if it’s better to disable it on the child or on the parrent as the child boxcollider was already there.

1 Like