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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Passing variables while scripting

Discussion in 'Scripting' started by caddi, Mar 28, 2020.

  1. caddi

    caddi

    Joined:
    Mar 23, 2020
    Posts:
    13
    Hi All,

    I'm new to Unity and coding, so I was hoping to get some help. Below is a Game Manager script I've written at this point it's just to track score and time. What I want to is be able to calc a final score taking the score minus the time it took. However, the way it's setup write now, I don't know how to get the value of currentScore into my Update method. Can anyone provide some guidance?

    Thanks!

    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.UI;
    3.  
    4. public class GameManager : MonoBehaviour
    5. {
    6.     public int currentScore;
    7.     public Text scoreText;
    8.     public Text timerText;
    9.     private float startTime;
    10.     private float timer;
    11.     // Start is called before the first frame update
    12.     void Start()
    13.     {
    14.         startTime = Time.time;
    15.     }
    16.  
    17.     // Update is called once per frame
    18.     void Update()
    19.     {
    20.         timer = Time.time - startTime;
    21.         timerText.text = "Time: " + (int)timer;
    22.     }
    23.     public void AddScore(int scoreToAdd) {
    24.         currentScore += scoreToAdd;
    25.         scoreText.text = "Score: " + currentScore;
    26.     }
    27. }
    28.  
     
  2. Stardog

    Stardog

    Joined:
    Jun 28, 2010
    Posts:
    1,890
    Create a new
    public int finalScore
    then put
    finalScore = currentScore - (int)timer;
    in Update.
     
    caddi likes this.
  3. caddi

    caddi

    Joined:
    Mar 23, 2020
    Posts:
    13
    perfect, thanks!