How to update UI.Text from a Prefab script?


Not sure if I’m doing this correctly but basically I have a 2 game objects in the Scene at design time.

First one (Pot) has has a rigidbody2d and a polygon collider 2d. Then I have a Canvas with a UI Text on it which I named ScoreText.

I also have a Prefab that I instantiate randomly from a script attached to the Main Camera.

Here’s the script that I attached to the prefab.

void OnCollisionEnter2D(Collision2D collision) {
  // How to update UI.Text with the score???

Appreciate any help.

This is pretty straightforward in Unity. You want to do the following things:

  1. When the first Pot starts, in the Start() Event, you want to grab the score text and remember it for all pots.

  2. When the collision happens, you want to increase the score on that text you previously grabbed.

    // We're making all Pots share a scoreText so that we only need to do GameObject.Find() for one of them. GameObject.Find() is very slow, and will cause the game to lag if there's many pots.
    static Text scoreText;
    // Score needs to be static, otherwise each Pot will have their own score.
    // For a full sized game, you should have a special GameObject that keeps track of game-wide variables like this, instead of having static variables in each MonoBehaviour. I like to call mine AppController.
    static int score;
    void Start( ) {
        if ( scoreText == null ) {
            // If this line results in an error, check the following: Is the ScoreText named exactly "ScoreText"? does it have a Text Component in it? Does it exist, and is it enabled, by the time the first Pot appears?
            scoreText = GameObject.Find( "ScoreText" ).GetComponentInChildren<Text>();
    void OnCollisionEnter2D(Collision2D collision) {
        scoreText.text = score.ToString();