Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Score not updating

Discussion in 'Scripting' started by herniecava, Sep 8, 2023.

  1. herniecava

    herniecava

    Joined:
    Aug 21, 2023
    Posts:
    1
    Please be nice, I´m new with Unity and programming... I´m working on this simple game, I want the score to increase by 1 or decrease by 1 depending on the selection of the player. Is kind of a test game, where you have to choose the correct answer. I have each answer on independent box colliders, but I can´t get the score updated if I click the correct or wrong answer... I made a script for the canva of UI, and a script for the text (wich is the same as the script for Game Manager), but nothing happens... What am I doing wrong? any suggestions?

    Thank you in advance...

    Here are the scripts:

    GameManager

    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.UI;
    3.  
    4. public class GameManager : MonoBehaviour
    5. {
    6.     public int score = 0;
    7.     public Text scoreText; // Variable para el objeto de texto
    8.  
    9.     void Start()
    10.     {
    11.         // Inicializa el texto del puntaje
    12.         UpdateScoreText();
    13.     }
    14.  
    15.     public void IncreaseScore()
    16.     {
    17.         score++;
    18.         UpdateScoreText();
    19.     }
    20.  
    21.     public void DecreaseScore()
    22.     {
    23.         score--;
    24.         UpdateScoreText();
    25.     }
    26.  
    27.     void UpdateScoreText()
    28.     {
    29.         if (scoreText != null)
    30.         {
    31.             scoreText.text = "Score: " + score;
    32.         }
    33.     }
    34. }
    UI Manager:
    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.UI;
    3.  
    4. public class UIManager : MonoBehaviour
    5. {
    6.     public Text scoreText; // Referencia al objeto de texto que mostrará el puntaje
    7.     private GameManager gameManager; // Referencia al GameManager
    8.  
    9.     void Start()
    10.     {
    11.         // Encuentra el GameManager en la escena
    12.         gameManager = FindObjectOfType<GameManager>();
    13.  
    14.         if (gameManager == null)
    15.         {
    16.             Debug.LogError("UIManager: No se encontró el objeto GameManager en la escena.");
    17.         }
    18.     }
    19.  
    20.     void Update()
    21.     {
    22.         // Actualiza el texto del puntaje en la pantalla con el valor del GameManager
    23.         if (gameManager != null && scoreText != null)
    24.         {
    25.             scoreText.text = "Score: " + gameManager.score;
    26.         }
    27.     }
    28. }

    Thank you!

    Luis.
     
  2. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    10,468
    Welcome but please note, this is nothing to do with 2D so best asked on the Scripting forum.

    I’ll move your post there for you.
     
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,563
    Time to start debugging! Here is how you can begin your exciting new debugging adventures:

    You must find a way to get the information you need in order to reason about what the problem is.

    Once you understand what the problem is, you may begin to reason about a solution to the problem.

    What is often happening in these cases is one of the following:

    - the code you think is executing is not actually executing at all
    - the code is executing far EARLIER or LATER than you think
    - the code is executing far LESS OFTEN than you think
    - the code is executing far MORE OFTEN than you think
    - the code is executing on another GameObject than you think it is
    - you're getting an error or warning and you haven't noticed it in the console window

    To help gain more insight into your problem, I recommend liberally sprinkling
    Debug.Log()
    statements through your code to display information in realtime.

    Doing this should help you answer these types of questions:

    - is this code even running? which parts are running? how often does it run? what order does it run in?
    - what are the names of the GameObjects or Components involved?
    - what are the values of the variables involved? Are they initialized? Are the values reasonable?
    - are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

    Knowing this information will help you reason about the behavior you are seeing.

    You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as
    Debug.Log("Problem!",this);


    If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

    You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

    You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

    You could also just display various important quantities in UI Text elements to watch them change as you play the game.

    Visit Google for how to see console output from builds. If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer for iOS: https://forum.unity.com/threads/how-to-capturing-device-logs-on-ios.529920/ or this answer for Android: https://forum.unity.com/threads/how-to-capturing-device-logs-on-android.528680/

    If you are working in VR, it might be useful to make your on onscreen log output, or integrate one from the asset store, so you can see what is happening as you operate your software.

    Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

    If your problem is with OnCollision-type functions, print the name of what is passed in!

    Here's an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

    https://forum.unity.com/threads/coroutine-missing-hint-and-error.1103197/#post-7100494

    "When in doubt, print it out!(tm)" - Kurt Dekker (and many others)

    Note: the
    print()
    function is an alias for Debug.Log() provided by the MonoBehaviour class.

    Once you learn more...

    How to report your problem productively in the Unity3D forums:

    http://plbm.com/?p=220

    This is the bare minimum of information to report:

    - what you want
    - what you tried
    - what you expected to happen
    - what actually happened, log output, variable values, and especially any errors you see
    - links to documentation you used to cross-check your work (CRITICAL!!!)

    The purpose of YOU providing links is to make our job easier, while simultaneously showing us that you actually put effort into the process. If you haven't put effort into finding the documentation, why should we bother putting effort into replying?
     
  4. tleylan

    tleylan

    Joined:
    Jun 17, 2020
    Posts:
    521
    I'm going to guess that you have IncreaseScore and DecreaseScore being called by something right? You can confirm that with a few Debug.Log() calls. Never rule out the obvious errors first. You have a scoreText Text property in both classes. The one in the GameManager shouldn't be needed as the UIManager creates a string and makes an assignment. It uses only the .score not the .scoreText property.

    Little issues like there is no reason to check for gameManager != null in the Update since you already tested for it in Start. May as well test for scoreText being null in Start as well and you don't have to check either one in Update.
     
  5. dlorre

    dlorre

    Joined:
    Apr 12, 2020
    Posts:
    700
    Instead of :

    Code (csharp):
    1.  
    2. gameManager = FindObjectOfType<GameManager>();
    3.  
    You can do this:
    Code (csharp):
    1.  
    2. [SerializeField] private GameManager gameManager;
    3.  
    And then select your UIManager object and drag your game manager object onto its Game Manager field in the inspector. That way you will be sure that the object exists and is initialized.

    The issue in your code is that you are updating your score in two scripts. Either UIManager or GameManager updates your score but not both. If you think that UIManager should handle it then move your UpdateScoreText() function to UIManager. It will naturally use gameManager.score.

    Code (csharp):
    1.  
    2.     public void UpdateScoreText()
    3.     {
    4.         if (scoreText != null)
    5.         {
    6.             scoreText.text = "Score: " + gameManager.score;
    7.         }
    8.     }
    9.  
    As for calling UpdateScoreText() from gameManager you just need a reference to your UIManager:

    Code (csharp):
    1.  
    2. [SerializeField] private UIManager uiManager;
    3.  
    and then

    Code (csharp):
    1.  
    2. uiManager.UpdateScoreText();
    3.  
    Finally, if you make use of the UpdateScoreText() function, then you don't need the code in Update() and you should remove it.

    Alternatively you can remove all the code in UIManager and let the GameManager handle it.
     
    Last edited: Sep 9, 2023