I’m new to Unity, but not a total newbie (have already created games with it). I’m having a really hard time adapting to the new Unity UI. I’ve been trying to add a score to my scene and can’t get it to work (update at run time), because no matter how hard I try to reference it to the code, it just doesn’t work!
Here’s what I’m doing:
I have created a UIText object in Unity
I have a scoring.cs code that increments my score (I’ve declared “using unityengine.UI”)
In scoring.cs I created a public Text object called score
I change that Text object at runtime: score.text="Score: " + iscore (where iscore is an int variable that I increment over time)
In Unity, I add scoring.cs to my UIText
Then I’m trying to associate my UI text from the editor to my public score. I’ve tried it all, can’t make it happen
I followed the instructions given to two similar threads in this forum, none worked. So I’m creating this new thread to see if someone can point me to the right direction or to an online tutorial I can follow. (The current official ones don’t go into details like that).
I think the way to fix it is to use Text instead of GameObject. I tried that but then I wasn’t able to use .FindWithTag with a Text object… Any ideas on how to make this work?
Here is yet another alternative way that worked for me using events:
public class ScoreCounter : MonoBehaviour
{
private Text _text;
void Start()
{
GameManager.OnScoreUpdated += UpdateScore;
_text = GetComponent<Text>();
if (_text != null)
_text.text = "SCORE\n" + GameManager.Instance.Score;
}
private void UpdateScore()
{
if (_text != null)
_text.text = "SCORE\n" + GameManager.Instance.Score;
}
void OnDestroy()
{
GameManager.OnScoreUpdated -= UpdateScore;
}
}
public class GameManager : Manager<GameManager>
{
public int Score;
public int ScoreMultiplier;
public delegate void ScoreUpdatedAction();
public static event ScoreUpdatedAction OnScoreUpdated;
private void PickedUpFish()
{
if (OnScoreUpdated != null)
OnScoreUpdated();
}
}
Player is meant to collect fishes in the game and PickedUpFish() is fired up every time that happens. Manager (class) is a generic singleton class for managers I use (audio, game state, etc.). This has the advantage of only being called when needed instead of every update.
TIm C’s code is admittedly more simple and should work with your existing code easier. I’m using this, because I have other objects which need to know when score is updated and I can just subscribe them to this event too.