Null Refrence exception when trying to assign a value to a TextMeshProUGUI Object in Unity

1 day ago 1
ARTICLE AD BOX

This is my first time using unity, and I've been trying to make a very simple operation. When an Apple falls into a basket, the basket will increment the score counter. However, Every time the apple hits the basket, a Null Reference Exception is thrown and my game crashes. I know I'm making a mistake somewhere, but I'm not quite sure where it is stemming from. Whenever the Null reference is thrown, I don't see any debug statements, and so i can't tell if those debug statements are reached, or if they aren't printed because of the exception? I also am under the impression that i have to attach my score counter to the corresponding TextMesh object as a component, and both the Script and Object must be named the same thing. My best guess is that I am not attaching the script to the TextMesh object correctly, or something on the unity side, because my code "looks" correct to me, in reference to some working examples that I have seen online. Thank you for taking the time to read my post, and thank you for your time.

Basket is a game object, and this is its accompanying script:

using UnityEngine; public class Basket : MonoBehaviour { public AppleScoreCounter scoreCounter; private void OnTriggerEnter2D(Collider2D other) { if (other.CompareTag("Apple")) { scoreCounter.GainScore(1); //do i need to write a destructer class for other??? Destroy(other.gameObject); Debug.Log("Trigger created by " + other.gameObject.name); } } }

And this is my score counter script, which is attached to a textMeshProUGUI Object:

using UnityEngine; using TMPro; public class AppleScoreCounter : MonoBehaviour { private TextMeshProUGUI scoreCounter; public int scorePoints; private void Awake() { Debug.Log("Awake started"); scoreCounter = GetComponent<TextMeshProUGUI>(); Debug.Log("Got past score counter"); } private void Start() { scorePoints = 0; //UpdateScoreUI(); Debug.Log("Got to end of start"); } //called when something happens(apple gets caught) public void GainScore(int points = 1) { scorePoints += points; UpdateScoreUI(); } private void UpdateScoreUI() { Debug.Log("Got to Update and broke"); scoreCounter.text = scorePoints.ToString(); Debug.Log("Score Points " + scorePoints); } }

And lastly, a screenshot of my hierarchy with my textMeshProUGUI Object inspector open.
enter image description here

Read Entire Article