I am getting NullReferenceException Error while trying to access Text Component , I tried twice but could not fineout the problem.

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

public class GameManager : MonoBehaviour
{
    public int TapCount=0;
    public float TapTime =60f;
    public GameObject TapCountText;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            TapCount++;
            Debug.Log(TapCount);
            Debug.Log(TapCountText.GetComponent<Text>().text = TapCount.ToString());   // IT showing Problem here
        }
        //TapCountText.GetComponent<Text>().text = TapCount.ToString();

        //EXTRA TEST
        if (Input.GetKeyDown(KeyCode.W))
        {
            Debug.Log("w");
        }
    }
}

@manjit047 - I apologize for the delay in response, I seem to be the only active moderator these days, and I am trying to keep up, but I have been very busy lately.

Always make sure that the GameObjects and Components you’re trying to access are not null before using them. This can help prevent NullReferenceException errors. You can do this by adding a null-check in your code.

You can try something like this (warning untested):

void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        TapCount++;
        Debug.Log(TapCount);
        if (TapCountText != null && TapCountText.GetComponent<Text>() != null)
        {
            TapCountText.GetComponent<Text>().text = TapCount.ToString();
            Debug.Log(TapCountText.GetComponent<Text>().text);
        }
    }
    //EXTRA TEST
    if (Input.GetKeyDown(KeyCode.W))
    {
        Debug.Log("w");
    }
}

I’ve added a null check for both TapCountText GameObject and the Text component. If either is null, the code inside the if block won’t execute, and you won’t get a NullReferenceException. If the null check fails, you should look back at your Unity Editor setup and see what’s missing or incorrectly configured.

Remember to assign your TapCountText GameObject in the Unity Editor, and make sure it contains a Text component.