Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice
  3. Dismiss Notice

Question I'm trying to make a check for a TMP Input but an error keeps occuring

Discussion in 'UGUI & TextMesh Pro' started by gionotfml, May 11, 2024.

  1. gionotfml

    gionotfml

    Joined:
    Oct 29, 2023
    Posts:
    2
    Mostly for fun I am making a charades app, I started working on a more advanced system to allow the user to change the minutes and seconds of the timer. Through a bit of struggling I managed to get no critical errors but whenever I attempt to change the input field text the following message appears in the console:
    "NullReferenceException: Object reference not set to an instance of an object
    SaveTime.Savetxt () (at Assets/Scripts/SaveTime.cs:18)"

    Here's the code I used to save the text into a playerPref so a scene can access it later (apologies that there are no comments, I usually forget to type those)
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5. using TMPro;
    6.  
    7. public class SaveTime : MonoBehaviour
    8. {
    9.     public TMP_InputField minInput;
    10.     public TMP_InputField secInput;
    11.     public int time;
    12.     public int tmpMin;
    13.     public int tmpSec;
    14.     public GameObject startButton;
    15.  
    16.     public void Savetxt()
    17.     {
    18.         if ((minInput.text == "") || (minInput.text == " "))
    19.         {
    20.             startButton.gameObject.SetActive(false);
    21.             Debug.Log("ERROR!!! Value of minutes is Null!!!");
    22.         }
    23.         else if ((secInput.text == "") || (secInput.text == " ") || (secInput.text == "  ") || (secInput.text == "0"))
    24.         {
    25.             startButton.gameObject.SetActive(false);
    26.             Debug.Log("ERROR!!! Value of seconds is Null!!!");
    27.         }
    28.         else
    29.         {
    30.             int tmpMin = int.Parse(minInput.text);
    31.             int tmpSec = int.Parse(secInput.text);
    32.             time = tmpMin * 60;
    33.             time = time + tmpSec;
    34.             PlayerPrefs.SetInt("Time", time);
    35.             startButton.gameObject.SetActive(true);
    36.             Debug.Log("Saved Text Correctly!");
    37.         }
    38.      
    39.     }
    40. }
    41.  
    According to the error it happens at a line where the code begins to check if the TMP input field is blank. It would be nice if someone could help me fix this issue, I'm pretty new to programming.