'Scores not updated when collided the second time
Im having problem with an endless runner game. The scores are not updating after the first object collided. The script is attached to a prefab object. After the first object collided, the score updated to +100, the second object collides, no change.
void Start()
{
player = GameObject.FindGameObjectWithTag("Gameship");
YourScore = GameObject.Find("Score").GetComponentInChildren<TextMeshProUGUI>();
}
void Update()
{
}
void OnTriggerEnter2D(Collider2D collision)
{
if (collision.tag == "Border")
{
Destroy(this.gameObject);
}
else if(collision.tag == "Gameship")
{
if(this.gameObject.tag == "Reward")
{
Destroy(this.gameObject);
ChangeScore(100);
}
}
}
void ChangeScore(int changeValue)
{
this.score += changeValue;
YourScore.text = score.ToString();
}
}
Solution 1:[1]
Assuming your score is starting from zero i.e. score = 0
, after colliding with Reward
tagged gameObject, your code does the following:
- The Score increases i.e.
score += 100 -> score = 100
- Updates the text.
text = "100"
- GameObject gets destroyed.
On destruction of gameObject, your score
variable also gets destroyed,
assuming you are instantiating this object again, the whole script is executed again means score = 0
, hence doing the above 3 steps over again and setting the text to 100 again which it already is.
I would suggest to use a Singleton class or just store the score variable in a different script that is not getting destroyed.
Solution 2:[2]
Currently you destroy the Object and so the scorevalue after it got triggered. You will need an extra class with a static variable which has a score variable which you increase instead of increasing the local one.
public class ScoreHolder {
public static long score = 0;
}
void Start() {
player = GameObject.FindGameObjectWithTag("Gameship");
YourScore = GameObject.Find("Score").GetComponentInChildren<TextMeshProUGUI>();
}
void OnTriggerEnter2D(Collider2D collision) {
if (collision.tag == "Border") {
Destroy(this.gameObject);
} else if(collision.tag == "Gameship") {
if(this.gameObject.tag == "Reward") {
ChangeScore(100);
Destroy(this.gameObject);
}
}
}
void ChangeScore(int changeValue) {
ScoreHolder.score += changeValue;
YourScore.text = ScoreHolder.score.ToString();
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Rajas |
Solution 2 | Rajas |