-1

I am making a simple coin system in my game using Unity and I ran into a problem.

Here is all the code that I have:

public class CoinSystem : MonoBehaviour
{
    public Text coinText;
    public int coinAmount;

    // Start is called before the first frame update
    void Start()
    {
        coinText = GetComponent<Text>();
    }

    // Update is called once per frame
    void Update()
    {
        coinText.text = coinAmount.ToString();
    }

When I run my game, I get this error:

NullReferenceException: Object reference not set to an instance of an object CoinSystem.Update () (at Assets/Scripts/CoinSystem.cs:21)

I've looked at multiple forums where our codes are very similar so I don't know what could be going wrong. Any help would be appreciated, thank you!

2 Answers2

1

The GameObject which you attached your code doesn't have a Text component.

Go the the inspector of the GameObject that contains this code (CoinSystem) and do

Add Component > Text
Daniel
  • 5,752
  • 4
  • 21
  • 48
0

You have to add the script to your Text component gameObject. If you are adding the script to a different gameObject and then referencing Text gameObject to the added script gameObject, then your Start() would look different as:

coinText.GetComponent<Text>();