Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by unity_VG19DPT6Sl_GcQ · Oct 04, 2021 at 02:48 PM · scorescore systemcoins

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:

link text

Thanks in advance for any help!

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
0

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.

Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image unity_VG19DPT6Sl_GcQ · Oct 04, 2021 at 09:41 PM 0
Share

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...

avatar image simiel7 · Oct 05, 2021 at 07:44 PM 0
Share

@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

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

129 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

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


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges