Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

289
Visualizações
Issue with score in game with unity c#

in my game the player have to collect a coins. The problem is that when player dies and starts a new game, the number of coins is not reset. For example:

starting new game and collectiong 15 coins, then dies

starting new game and number of coins i set to 15, not 0

How can I fix that??

Script used for displaying score on the screen:

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

public class Score : MonoBehaviour
{
    Coin coin;
    void Update()
    {
        coin = FindObjectOfType<Coin>();
        GetComponent<Text>().text = coin.GetScore().ToString();
    }

Script used for adding coins to score:

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

public class Coin : MonoBehaviour
{
    float speed = 10f;
    public static int score = 0;
    void Update()
    {
        transform.position += Vector3.left * speed * Time.deltaTime;
    }
    private void OnTriggerEnter2D(Collider2D collision)
    {
        score += 1;
    }
    public int GetScore()
    {
        return score;
    }
}

I also need to say that I was messin around with PlayerPrefs with that score to make some highscore concept, but I deleted every PlayerPrefs I did. Thanks a lot.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

This is the problematic line:

public static int score = 0;

A variable declared "static" will last for as long as the runtime does, even if the object it's tied to is destroyed (it's a value shared across all coin objects).

Ideally, you'd make it non-static (which is what Unity expects).

public int score = 0;

If you then re-create the Coin object whenever the player dies, unity will handle the cleanup for you.

Alternatively, you could add a "Reset" method to the Coin class...

public int GetScore()
{
    return score;
}

public void Reset()
{
    score = 0;
}

I answered a question which goes into statics in more detail and may be of interest.

Normally when a class has variables, every time you make a new instance of the class, it gets its own copies of each variable.

(You can create two Animal classes and give each one a different Name)

A static variable is different. Instead of each instance having its own copy of the variable, they all share the same one.

So if you set animal1.StaticName, you'd change animal2.StaticName as well. More to the point, you don't even need to make an animal, you can just set Animal.StaticName directly.

So... A static variable can be read/set (and static methods can be executed) even if you haven't created an instance of the class.

Oh and... If you do decide to keep the score static, you don't need to find a specific object to get the score...

void Update()
{
    GetComponent<Text>().text = Coin.score.ToString();
}
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda