You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity输入框传入空值报错问题求助(猜数字游戏开发)

猜数字游戏空输入崩溃问题修复

核心问题

你的代码崩溃的根本原因是在检查输入是否为空之前,就调用了int.Parse(userInputValue)。当输入为空字符串时,int.Parse会直接抛出FormatException导致程序崩溃,后续的空值判断根本没机会执行。

修复后的代码

改用int.TryParse替代int.Parse,它会尝试转换输入字符串,成功时返回true并输出转换后的整数,失败时返回false且不会抛出异常。同时调整逻辑顺序,先验证输入有效性:

// 随机数变量
public int randomNum;

// 用于判断输入是否过小/过大的阈值
private int randomNumSmall;
private int randomNumBig;

// 用户输入框
public InputField userInput;

void Start()
{
    // 计算阈值
    randomNumSmall = randomNum - 10;
    randomNumBig = randomNum + 10;
}

void Update()
{
}

public void OnButtonClick()
{
    string userInputValue = userInput.text.Trim(); // 去除首尾空格,避免用户输入空白字符的情况

    // 先判断输入是否为空或空白
    if (string.IsNullOrEmpty(userInputValue))
    {
        Debug.Log("请输入一个数字");
        return; // 直接返回,不执行后续逻辑
    }

    // 尝试转换输入为整数
    if (int.TryParse(userInputValue, out int answer))
    {
        // 猜数字逻辑
        if (answer < randomNum)
        {
            if (answer < randomNumSmall)
            {
                Debug.Log("太小啦!差得远呢!");
            }
            else
            {
                Debug.Log("小了一点!");
            }
        }
        else if (answer > randomNum)
        {
            if (answer > randomNumBig)
            {
                Debug.Log("太大啦!差得远呢!");
            }
            else
            {
                Debug.Log("大了一点!");
            }
        }
        else
        {
            Debug.Log("答对了!");
        }
    }
    else
    {
        // 兜底判断,避免意外情况
        Debug.Log("请输入有效的整数");
    }
}

额外优化建议

既然你提到“无法在输入框中输入字符串和浮点类型数据”,可以直接在Unity编辑器里设置InputField的Content Type为Integer Number:

  • 选中你的InputField组件
  • 在Inspector面板找到Input Field -> Content Type
  • 选择Integer Number

这样输入框会自动限制用户只能输入整数,从源头避免非数字输入的问题,进一步降低崩溃风险。

内容的提问来源于stack exchange,提问作者Thin_Grease06

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 23:28:11