Getting started with Unity
It would be more engaging to show the player a “Success!” when the ball lands in the bucket. To display text, you’ll need a GameObject with a text component.
Two new GameObjects have been added to the scene – Canvas and Text (TMP). Select Text (TMP) and rename it to ResultText. Clear “New Text” from the Text property of the TextMeshPro – Text (UI) component.
Next, you will write C# code to update the UI with “Success!”.
In the Project window, double click the WinMonitor script to open it and replace the existing code with the following:
using TMPro;
//1
public class WinMonitor : MonoBehaviour
{
//2
public TMP_Text resultTextRef;
//3
private void OnCollisionEnter(Collision collision)
{
//4
resultTextRef.text = "Success!";
}
}
Here is what the code is doing:
A MonoBehavior has several callback methods, often called “magic methods”, that you can reference in your scripts. There are three important callbacks for collisions:
The inspector can be used to easily add references to GameObjects and/or their components instead of writing C#. Doing this also lets you manipulate values at runtime if needed. Select Bucket and click on the bullseye icon next to the Result Text Ref property of the WinMonitor component. Pick the ResultText GameObject.
Note: Be careful when changing values when the game is running! The new values will not be serialized (saved) when you stop play mode.
That’s it! Press the Play button to see what happens.