【问题标题】:Int is not showing in text fieldInt 未显示在文本字段中
【发布时间】:2019-08-24 04:46:26
【问题描述】:

我的目标是让用户通过将输入的黄金数量乘以 1000 来输入他们必须转换成现金的黄金数量。每个金条价值 1000 现金。然后我想显示总数是多少。

另外,是否有另一种方法可以使用更新功能来不断更新它?我觉得它的性能太密集了。

我得到这个错误:

FormatException:输入字符串的格式不正确 System.Int32.Parse (System.String s) (在 /Users/builduser/buildslave/mono/build/mcs/class/corlib/System/Int32.cs:629) NSExchangeManager.ExchangeManager.Update () (在 Assets/ExchangeManager.cs:37)

我尝试交换 int.Parse() 的转换位置,但没有成功。

if(inputText.text != null)
{
    // Get input text
    string amountOfGold = inputText.text;
    // Set gold value
    int goldValue = 1000;
    // Multiply goldvalue by amount of gold
    int total = goldValue * int.Parse(amountOfGold);

    // Show the total in the 'money text'
    money.text = "$" + total.ToString();
    // Show amount of gold typed
    gold.text = amountOfGold;
}

【问题讨论】:

  • int.Parse(amountOfGold) 导致错误。因为文本值(可能是 string.Empty)无法转换为 int。更改 if 条件以使用 int.TryParse

标签: c# parsing unity3d int


【解决方案1】:

非常感谢您的帮助!这就是最终对我有用的方法。

if(inputText.text != null)
        {
            // Get input text
            string goldInput = inputText.text;
            int goldInputNum;
            int.TryParse(goldInput, out goldInputNum);

            // Set gold value
            int goldValue = 1000;

            int total = goldValue * goldInputNum;

            // Show the total in the 'money text'
            money.text = "$" + total.ToString();
            // Show amount of gold typed
            gold.text = goldInput;
        }

【讨论】:

    【解决方案2】:

    输入的字符串格式不正确

    表示文本框(字符串)的值不是可以解析为int的有效数值。你应该改用TryParse()

    int gold = 0;
    int.TryParse(amountOfGold,out gold);
    int total = goldValue * gold;
    

    【讨论】:

    • 由于某种原因我仍然收到错误:#1 Assets/ExchangeManager.cs(42,21): error CS1502: The best overloaded method match for int.TryParse(string, out int)' has some invalid arguments #2 Assets/ExchangeManager.cs(42,44): error CS1620: Argument #2' is missing `out'修饰符
    • 为了有一个内联默认值,我通常使用int gold = int.TryParse(amountOfGold, out gold) ? gold : 0;,在我看来这会清理一些东西。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-27
    • 2023-04-03
    • 1970-01-01
    • 2019-12-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多