Reputation: 796
I was trying to implement a Score System into my Game. I got two variables,
public int maxScore;
public int currentScore;
To set the currentScore, I get the maxScore and throw it into currentScore:
currentScore = maxScore;
So the Player has the maximum amount of points if he starts the Game. If he now is to slow, I decrease the currentPoints per Second with
IEnumerator CurrentScore()
{
currentScore -= 1;
yield return new WaitForSeconds(5); //I'm using 5, because 1 does not equals a second
}
and call it by saying
StartCoroutine(CurrentScore());
If I now look into the Game, it all looks fine:
As the Game starts, both are on 3000:
If the timer runs to a specific value, the currentScore decreases, but the MaxScore stays. As it should:
However, as soon as the WinScreen PopsUp, both values start to decrease rapidly, instead of only one decreasing:
I have this script Attached to the Text that shows the Current (Earned) Points, and the Possible Points:
using UnityEngine;
using UnityEngine.UI;
public class WinScreenScore : MonoBehaviour {
//Load the classes
public GameManager manager;
//To get our Text
//public GameObject scoreText;
Text max;
Text current;
//As soon as the Thread awakes, load the Text
void Awake()
{
max = GetComponent<Text>();
max.text = manager.maxScore.ToString();
}
void Update()
{
current = GetComponent<Text>();
current.text = manager.currentScore.ToString();
}
}
Script on the Text which displays the currentScore (Earned Points):
And on the Possible Points:
I can't figure out why both values are decreasing rapidly after the Winscreen got shown.
Thanks for helping!
Upvotes: 1
Views: 92
Reputation: 2167
WinScreenScore runs on both text objects. In the Update method, you get the component that is Text and set it to the current score. So for you max score this is happening. The awake gets the text component and sets the text to the max score from the game manager. Then in the update, you set THE SAME text component to the current score. Basically, you are filling max and current with the same text component. Solution : create public references to the game objects that hold the text components and then get the two separate texts. The script does not need to run on both objects.
CodeExample :
public GameManager manager;
public GameObject max, achieved;
Text currentText, maxText;
void Start()
{
currentText = achieved.GetComponent<Text>();
maxText = max.GetComponent<Text>();
maxText.text = manager.maxScore.ToString();
}
//Since the current Score needs to be updated
void FixedUpdate()
{
currentText.text = manager.currentScore.ToString();
}
Now you can set current and max independently. Also using GetComponent in Update is a bad idea since its a heavy operation. Try to use only in places that run once.
Upvotes: 2