Cant Link Ammunition And Text

Does anyone know how to fix my issue? I have text that will not update with my ammo. It gives me this error in the console: “NullReferenceExeption: Object reference not set to an instance of an object” (I took out the important parts in the script down below.)

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

public class GunScript : MonoBehaviour
{
    public int maxAmmo = 100;
    private int currentAmmo;


    Text ammoTxt;

    void Awake()
    {
        ammoTxt = GetComponent<Text>();
    }

    void Start()
    {
        maxAmmo = 100;
        currentAmmo = maxAmmo;
    }

    void Update()
    {
        ammoTxt.text = gameObject.GetComponent<GunScript>().currentAmmo.ToString();
    }

    public void Shoot()
    {
        currentAmmo--;
    }
}

It would be helpful if you mentioned which line the error occurs, but it is a good idea to check if GetComponent or similar methods are returning null before trying to use their returned reference. Especially when debugging this kind of issue.

Do stuff like this:

    void Awake()
    {
        ammoTxt = GetComponent<Text>();
        if (ammoTxt == null)
        {
            Debug.Log("ammoTxt is null in Awake() GunScript.cs");
        }
    }

Also, what are you doing in Update? It makes no sense. You’re effectively using GetComponent to get a reference to itself just to access a private variable.

This:

    void Update()
    {
        ammoTxt.text = gameObject.GetComponent<GunScript>().currentAmmo.ToString();
    }

and this:

    void Update()
    {
        ammoTxt.text = currentAmmo.ToString();
    }

do the same thing.