- Home /
For some reason my score isn't incrementing
I'm trying to make a coin counter for my 2D game but for some reason its not incrementing even thought i told it to do so. Does anyone know what i'm doing wrong
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class coin : MonoBehaviour
{
public Text ScoreText;
public int coinAmount = 0;
private void Start()
{
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Player"))
{
Destroy(gameObject);
// here is where i increment the counter
coinAmount = coinAmount + 1;
ScoreText.text = coinAmount.ToString();
}
}
}
Answer by ADiSiN · Jun 01, 2020 at 01:51 PM
Hi!
Your overall logic of functions is kinda inverted. To understand it better - look at this pic: It describes your implemented logic: each coin class has it's own coinAmount variable, so even if you wouldn't destroy them before desired increasement you would stuck with 1 score, because each one of coin will increment it's own coinAmount from 0 to 1 and then assign the Text component to it.
Look at this pic: The logic here is: we want to have Player class that has the coinAmount variable that we will adjust upon picking up coins so previous increasement will stay, because it's the same instance of the variable as before, not separated in different instances of classes.
The code itself could look like this:
public class Player : MonoBehaviour
{
public int coinAmount;
public Text ScoreText;
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Coin"))
{
Destroy(collision.collider.gameObject);
// here is where i increment the counter
coinAmount = coinAmount + 1;
ScoreText.text = coinAmount.ToString();
}
}
}
As you can see it's not much more different from your, so you did pretty much got it right, but the code is inside Player class and we are checking for "Coin" tag.
Hope it helps.
Answer by KoenigX3 · Jun 01, 2020 at 12:29 PM
If the script is on the GameObject you are about to destroy, make sure that destroying is the last thing you do. Otherwise the rest of the script won't get called, simply because the script component also gets destroyed.
Your answer
Follow this Question
Related Questions
Counting and comparing score of two players 2 Answers
Collider not functioning correctly 1 Answer
How can I keep a global score updatable from multiple GameObjects 1 Answer
New score each level 1 Answer
How to FadeIn Score one by one?? 1 Answer