- Home /
score display not showing
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "flower")
{
score += 1;
Debug.Log(score);
}
}
I have a projectile that when hits the collider of the flower enemy type it adds a point to the overall score. The Debug.Log does show the score increasing yet the display text in the canvas doesnt up date. any idea why that might be?
Here's some screenshots of in game.
Answer by Getsumi3 · Jun 10, 2020 at 06:48 PM
Hi
I don't see (on your screenshots) which script is making the job of updating the UI.
You'll need a script, like DataManager or GameManager, that will handle UI updating and data saving.
Here is a little example(not tested). Attach this script to an empty gameObject in your scene:
using UnityEngine;
using UnityEngine.UI;
public class GameManager : MonoBehaviour
{
public int score = 0;
public Text scoreText;
public void AddScore(int _score)
{
//updating our variable
score += _score;
//updating the UI text
scoreText.text = score.ToString();
}
}
And to your Flower.cs script add this changes:
//Attach the empty object with GameManager script to this variable in inspector
public GameManager GM;
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "flower")
{
//adding score and updating UI
GM.AddScore(1);
Debug.Log(score);
}
}
I did everything listed here, still seems to not update the UI. I called it Point $$anonymous$$anager, and added it to the players projectile. so when it hits the Flowers collider it would add to the point manager. Now weirder yet, after I test the game in Unity the Score amount doesn't reset? I've never seen this before..
I should mention that I'm using prefabs of the scoreText, and the projectiles. not sure how to do this without using prefabs. if that's the reason causing this, I'd appreciate to hear an alternative.
scoreText should be an actual object as a child in your canvas
Initialize your pointee$$anonymous$$anager as a static variable:
public class Pointer$$anonymous$$anager: $$anonymous$$onoBehaviour
{
public static Pointer$$anonymous$$anager i;
//everything else remains as before
}
And on your projectile script you don't need anymore to attach a reference of Pointer$$anonymous$$anager so change it this way:
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "flower")
{
//adding score and updating UI
Pointer$$anonymous$$anager.i.AddScore(1);
Debug.Log(score);
}
}
Your answer
Follow this Question
Related Questions
Canvas breaks on scene change 0 Answers
Simple score system breaking crates 1 Answer
score counter is not accurate 1 Answer
2D project - Sprite not visible in scene view 1 Answer
2D colliders not working with UI? 0 Answers