Home > Mobile >  Score in Unity game only increases by 1 and then stops
Score in Unity game only increases by 1 and then stops

Time:05-03

I am trying to create a score in unity where if you collect coins (in my case shells) the score goes up by 1 each time, however, the score increases by 1 and then stops increasing and I am not sure why.

Script attached to coin (shell):

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

public class ShellController : MonoBehaviour
{
    private float coin = 0; // is it because every time player collides with shell, this resets the score back to zero? if so, how do I only set it to zero once, in the beggining? 
    public TextMeshProUGUI textCoins;
    // Start is called before the first frame update
    private void OnTriggerEnter2D(Collider2D collision)
    {
        if(collision.tag == "Player")
        {
            SoundManagerScript.PlaySound("winCoin");
            coin   ;
            textCoins.text = coin.ToString();
            Destroy(gameObject);
            
        }
    }
}

This is the code attached to the label (text) which displays the score:

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

public class ScoreTextScript : MonoBehaviour
{
    Text text;
    public static int coinAmount;
    // Start is called before the first frame update
    void Start()
    {
        text = GetComponent<Text>();
    }

    // Update is called once per frame
    void Update()
    {
        text.text = coinAmount.ToString();
    }
}

CodePudding user response:

Because ShellController will be destroyed which player collision by OnTriggerEnter2D event, but ShellController initials coin as 0 for each shell game object, so that why you might always get 1 instead of increase number.

private float coin = 0;

coin   ;
textCoins.text = coin.ToString();

We can try to increase coinAmount field from ScoreTextScript game Object from each ShellController game object and keep the value in ScoreTextScript game object.

private void OnTriggerEnter2D(Collider2D collision)
{
    if(collision.tag == "Player")
    {
        SoundManagerScript.PlaySound("winCoin");        
        textCoins.coinAmount  ;
        Destroy(gameObject);
    }
}

CodePudding user response:

This is a simple collision method for UNIITY to collect gold coins void OnTriggerEnter(Collider col) {

    if (col.gameObject.tag == "Player")//If the collision object is the player
    {
     money  ;//money plus one
     Destroy(this.gameObject);//Destroy gold coins
    }
}

Create a gold coin model and paste the above code in its C# code to collect gold coins. If you need to modify the display information of money on the existing UI

     GameObject ifCollect = GameObject.Find("/Canvas/TextTwo");//" "Where is your UI
     ifCollect.GetComponent<Text>().text = money.ToString();//Change money
  • Related