- Home /
Add Coin Score to Time Score
Hello, guys. Everytime my player collides with a coin it adds 50 points, and every second it adds 100 points. But ingame I can see the time score being added, and when I catch a coin I see the 50 there, but the 50 is not added to the time score, it's like the same text has 2 scores. Here are my scripts:
My scoreManager:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ScoreManager : MonoBehaviour {
public Text puntuacionGameplayText, puntuacionFinalText;
private int scorePerTick = 100;
private int scoreCoin = 50;
private float nextTimeToScore;
private int totalScore = 0;
private bool juegoAcabado = false;
// Use this for initialization
void Start () {
//Empezamos teniendo el cuenta en tiempo para que el score no empiece ya en 100
nextTimeToScore = Time.timeSinceLevelLoad + 1;
}
// Update is called once per frame
void Update () {
if (!juegoAcabado)
{
if (Time.timeSinceLevelLoad >= nextTimeToScore)
{
AumentarScore();
nextTimeToScore = Time.timeSinceLevelLoad + 1;
}
}
}
public void AcabarJuego()
{
juegoAcabado = true;
int maximaPuntuacion = PlayerPrefs.GetInt("Puntuacion", 0);
int puntuacionTotal = GetTotalScore();
string puntuacionString = "Tu puntuación ha sido de \n " + puntuacionTotal;
if (maximaPuntuacion < puntuacionTotal)
{
puntuacionString += "\n ¡Nueva puntuación maxima alcanzada!";
PlayerPrefs.SetInt("Puntuacion", puntuacionTotal);
PlayerPrefs.Save();
}
puntuacionFinalText.text = puntuacionString;
}
void AumentarScore()
{
totalScore += scorePerTick;
puntuacionGameplayText.text = totalScore.ToString();
}
public int GetTotalScore()
{
return totalScore;
}
}
My coin score is within the character script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Personaje : MonoBehaviour {
public float aceleracion = 0.0015f;
public float speed = 5;
public float leftRightSpeed = 5;
public int segundosInmune = 3;
public int vidaMaxima;
public GameObject hitFX;
public AudioSource hitSound;
public Text puntuacionGameplayText, puntuacionFinalText;
private int scoreCoin = 50;
private int totalScore;
private int vidaActual;
private Rigidbody rigidBody;
private Animator animator;
private bool isInmune = false;
private float nextTimeKickInmune = 0;
private float speedMultiply = 0;
public Text lives;
public float jumpForce = 10;
public bool isGround = true;
// Use this for initialization
void Start()
{
rigidBody = GetComponent<Rigidbody>();
animator = GetComponentInChildren<Animator>();
rigidBody.freezeRotation = true;
vidaActual = vidaMaxima;
lives.text = "Lives = " + vidaActual;
}
// Update is called once per frame
void Update()
{
//Vamos a ir incrementando la velocidad a la que tiene que ir en intervalos regulares hasta alcanzar la velocidad que le corresponde
speedMultiply += aceleracion;
if (speedMultiply > 1) speedMultiply = 1;
float realSpeed = speedMultiply * speed;
float realLeftRightSpeed = speedMultiply * leftRightSpeed;
Vector3 movimiento = Vector3.forward * realSpeed * Time.deltaTime;
if (Input.GetKey("left"))
{
movimiento += Vector3.left * realLeftRightSpeed * Time.deltaTime;
}
if (Input.GetKey("right"))
{
movimiento += Vector3.right * realLeftRightSpeed * Time.deltaTime;
}
if (Input.GetKeyDown("space") && isGround)
{
GetComponent<Rigidbody>().velocity = new Vector3(rigidBody.velocity.x, jumpForce);
animator.SetTrigger("Jump");
isGround = false;
}
transform.position += movimiento;
if (isInmune)
{
if (Time.timeSinceLevelLoad >= nextTimeKickInmune)
{
AcabarInmunidad();
}
}
lives.text = "Lives = " + vidaActual;
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "Floor")
{
isGround = true;
}
}
public void DetenerPersonaje()
{
speed = 0;
leftRightSpeed = 0;
animator.SetTrigger("Detener");
}
void CoinScore()
{
totalScore += scoreCoin;
puntuacionGameplayText.text = totalScore.ToString();
}
public void RestarVida()
{
if (!isInmune)
{
hitFX.SetActive(true);
hitSound.pitch = Random.Range(0.8f, 1.2f);
hitSound.Play();
vidaActual--;
Debug.Log("Vida actual " + vidaActual);
}
}
public bool EstaMuerto()
{
if (vidaActual <= 0) return true;
else return false;
}
public void AcabarInmunidad()
{
//rigidBody.isKinematic = false;
isInmune = false;
}
public void EmpezarInmunidad()
{
if (!isInmune)
{
//rigidBody.isKinematic = true;
isInmune = true;
nextTimeKickInmune = Time.timeSinceLevelLoad + segundosInmune;
}
}
public void BloqueGolpeado()
{
RestarVida();
EmpezarInmunidad();
}
public void OnTriggerEnter(Collider other)
{
if(other.tag == "Enemy")
{
BloqueGolpeado();
}
if (other.gameObject.tag == "Coin")
{
CoinScore();
}
}
}
And here is a video of that situation:
Thanks in advance for any help!
Answer by simiel7 · Oct 04, 2021 at 04:07 PM
Hi!
After a quick review and based on the video you attached, I think the problem is trivial. There is no connection between the totalScore in the Personaje and the ScoreManager classes.
They are separate things, you defined the totalScore in both classes and they will manage them separately. The Personaje starts to count from 0, because 0 is the default value of the int if you not define it expicitely. So it will start to count from 0 and when you pick up a coin, it will add up 50 to it, and again, and again (it does not care, if the ScoreManager or any other class has a variable with the same name). --> For this part to understand the work behind the programming language, search for Scope or Visibility of variables in C#.
Solving quickly your issue currently (not the best)
Probably you attach the same puntuacionGameplayText text field via the Editor, so it is a common thing in both classes. You can get the actual value of this field with puntuacionGameplayText.text and you can cast this value to a int, for example int.Parse(...), in this case int castedTotalScore = int.Parse(puntuacionGameplayText.text). After the casting you can add the neccesary amount, like 50 if picked up a coin in the following way: castedTotalScore + coinScore and you can set back this value to the text field you have.
int castedTotalScore = int.Parse(puntuacionGameplayText.text);
puntuacionGameplayText.text = castedTotalScore + coinScore;
After this you should see the correct value, because it will get the actual value and add the value to that and set back the summarized value to the text field.
As I said, it is just a quick and dirty solution for your problem and you should check out the Parse method, handle the errors and so on.
Or refactor / rewrite the whole concept and structure your logic into a different format and extract the TotalScoreText field and its logic into a separate class and only this class can update this component, instead of divide this logic into multiple places. And everything else, you call this separate class which will handle the update itself as a self-contained class.
Hey, simiel7, thanks for the reply.
Where should I write those 2 lines within my script? Sorry, it is my first Unity project and this is kinda blowing my $$anonymous$$d, and I don't understand why...
@unity_VG19DPT6Sl_GcQ Hi!
Into the CoinScore and AumentarScore, but be aware what you write inside them. I mean in the AumentarScore probably you should use scorePerTick instead of coinScore.
Your answer
Follow this Question
Related Questions
How to increase score by one per second when you are holding an object 2 Answers
Score and Highscore - Highscore not saving, loading, or displaying. 0 Answers
Score not increasing after killing 1 enemy 2 Answers
Can´t Get My Score System To Work. Help! 0 Answers
How to check if variable is equal to range of integers 2 Answers