[C#] Retrieve and Display UIText

Hello!

I work on a very small project in which a Score [UIText element] is displayed. Whenever a player reaches a certain Score a text should be displayed. [Again with a UIText element]. In this text element i have some lines like “Well Done”, “Keep on Going”, “Almost there!”. So far it works quite well. Once a goalScore is reached the score vanishes for a moment and the message is displayed. After the next shot the text message vanishes and the regular score is displayed again.

The Score.cs script-snippet:

        void Update ()
        {
            GetComponent<GUIText>().text = "Score: " + score;
   
            if (goalScore.Equals(10000))
                GetComponent<GUIText>().text = "Well Done!";
   
            if (goalScore.Equals(15000))
                GetComponent<GUIText>().text = "Bow Your Head!";

            goalScore = score;
        }

Although it does what it should there must certainly be a better and more elegant way to solve this. All i want to do is to retrieve predefined messages from the UIText element upon reaching goalScore[1], [2], [3] … without writing dozens of (probably) unnecessary lines of code.

As i am rather new to C# scripting and Unity i hope you’ll explain things a little more in depth in case you provide code examples. Links to the documentation so i can learn and figure things out myself would also be much appreciated!

First of all, you should not use GetComponent in Update. It is slow and you rather should use a reference. Second, you should use the new UI system. Third, you should only check for a certain score when the score actually changes, which I assume happens in a different script. Fourth, checking for the exact score is a bad idea when it is possible to get more than one point at a time.

3 Likes

Thanks for taking the time to reply. What you pointed out is most helpful to me.

Score checks are done in a different script indeed. They are checked and updated dynamically. The only static portion would have been 10000 → display message 1, 150000 → display message 2, … and so forth. My thought was that i could only do this by checking for the exact score values. Obviously this wasn’t a good idea.

With the information i could gather from your link i should be able to do things correctly now. Thanks again!