I want create to simple date checking functionality using InputFields. I set InputFields to only take integers with 2 to 4 character limit. In Update method i’m checking if it’s a leap year, but if I delete the whole number in the box I get FormatException error blocking the app. I use int.Parse() to convert InputField.text to integer and I think there is the problem, because when I delete number there is null. Is there is a way to implement exception, which will not stop the application?
Here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ButtonDisableTest : MonoBehaviour
{
[Header("Inputs")]
public InputField YearField;
public bool leapYear;
public int intYear;
public void Start()
{
// getting the real date from another script
GameObject Canvas = GameObject.Find("Canvas");
DateTest date = Canvas.GetComponent<DateTest>();
// here i need this or there will be FromatException from the start
YearField.text = date.iYears.ToString();
}
// Update is called once per frame
public void Update()
{
// getting the real date from another script
GameObject Canvas = GameObject.Find("Canvas");
DateTest date = Canvas.GetComponent<DateTest>();
int intYear = int.Parse(YearField.text);
if (intYear % 4 == 0)
{
if (intYear % 100 == 0)
{
if (intYear % 400 == 0)
leapYear = true;
else
leapYear = false;
} else
leapYear = true;
} else
leapYear = false;
}
public void onButtonPressed()
{
Debug.Log("Button pressed" + leapYear);
}
}