Text never displays count variable

I have a game where I’m throwing a box into a square and want to count this box. When the box hits the trigger event it will count the box, but when I try to display that in a text object it does not show up. The counted variable never seems to make it out of the trigger event and I’m not sure why. Any help would be greatly appreciated!

Here’s the code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

namespace MiniGames
{
public class BoxStorage : MonoBehaviour
{
[SerializeField] GameObject boxCountTexty;
Text boxCountText;
public int boxCount;

    private void Start()
    {
        boxCountText = GetComponent<Text>();
        boxCountTexty.SetActive(true);
    }

    private void Update()
    {
        boxCountText.text = boxCount.ToString(); //Doesn't change the text object
        Debug.Log("boxes: " + boxCount); //Doesn't print in console
    }

    public void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.tag == "Box")
        {
            boxCount++;
            Debug.Log("boxes: " + boxCount + "in trigger"); //This prints in console
            Rigidbody2D colRb = collision.gameObject.GetComponent<Rigidbody2D>();
            colRb.isKinematic = false;
        }
    }

    public void OnTriggerExit2D(Collider2D collision)
    {
        if(collision.gameObject.tag == "Box")
        {
            boxCount--;
        }
    }
}

}

@katiepillar I am assuming this script is attached to the cube which is being tossed? if that’s the case…the update method’s logic is not affecting the text because there is no actual reference to a Text component.

you are using GetComponent without an explicit reference to a game object; this means the code is going to return the very first Text component it finds that is attached to the same game object as the script itself. in your case, it appears this script is attached to the cube and I assume your cube does not have a Text component attached to it.

judging by your code, I would think the game object that has the Text component is “boxCountTexty”. if that’s right, update you’re GetComponent reference in Start to grab the component from that game object instead of the cube the script itself is attached to; it should look something like this:

boxCountText = boxCountTexty.GetComponent<Text>();

also, consider removing your logic from the update method and implement it within the trigger event as well; there is no benefit to to having that logic in the update method; the text only needs to change when the trigger is activated.