【问题标题】:Unity is saying my array is overflowing and crashesUnity 说我的数组溢出并崩溃
【发布时间】:2022-06-11 21:23:32
【问题描述】:

我一直在尝试编写一段代码,它需要输入钱并用数字(1000 到 1000、1,000,000 到 100 万等)重写它。到目前为止,我一直无法通过Unity 告诉我,我的数组在崩溃之前发生了堆栈溢出,但我不明白它为什么会溢出。我错过了一些巨大的东西还是这里不合适? Unity 一直给我错误“请求的操作导致堆栈溢出,MoneyTruncate() (at Assets/Scripts/Money.cs:60”),这是与此 void 中的数组有关的行。

    {
        string[] Numerals = new string[]{" ", "thousand", "million", "billion"} ;
        int i = 0;

        TotalMoneyFloat = (TotalMoney / (10 ^ (i * 3)));
        TotalMoneyFloatLimit = (TotalMoney / (10 ^ ((i + 1) * 3)));

        //current iteration of Numeral is correct- greater than current numeral, less than next
        if(TotalMoneyFloat >= 1 && TotalMoneyFloatLimit < 1)
        {
            TotalMoneyText.GetComponent<Text>().text = "$" + TotalMoneyFloat.ToString("0.00") + " " + Numerals[i];
        }

        //current iteration of Numeral is too high- less than current numeral
        if(TotalMoneyFloat < 1)
        {
            i--;
            MoneyTruncate();
        }

        //current iteration of Numeral is too low- greater than current numeral
        if(TotalMoneyFloatLimit >= 1)
        {
            i++;
            MoneyTruncate();
        }

        //i is at its limit for number of numeral available- i has reached max value for the array but money is higher than  
        if(i > 3 && TotalMoneyFloat <= 1)
        {
            TotalMoneyText.GetComponent<Text>().text = "$" + TotalMoneyFloat.ToString("0.00") + " " + Numerals[i];
        }
    }```

【问题讨论】:

  • 发布的代码在何处/何时执行?在我对已发布代码的小跟踪中……特别是在最后一个if 语句中……if(i &gt; 3 &amp;&amp; TotalMoneyFloat &lt;= 1) { ………? ……据我所知……i 永远不会大于 3。i 只会是 -1、0 或 1。所以我不确定“为什么”你会期望 i 是除此之外的任何其他值-1、0 或 1。
  • 代码的其余部分有一些段,当“商店”出现并产生货币时,这些段调用函数将货币值打印到文本框:IEnumerator Stand1() { yield return new WaitForSeconds(GetComponent&lt;Shop1&gt;().Shop1Timer); TotalMoney += GetComponent&lt;Shop1&gt;().Shop1Revenue; CurrentTimerShop1 = 0; MoneyTruncate(); StartCoroutine(Stand1()); }
  • 嗯……好吧……那么,最后一个if 声明是为了什么?正如我所提到的,ifs 条件永远不会评估为true……所以它的目的是一个谜。这行代码……TotalMoneyText.GetComponent&lt;Text&gt;().text = "$" + TotalMoneyFloat.ToString("0.00") + " " + Numerals[i];……永远不会被执行。这是故意的吗?
  • 如果玩家进入万亿,它会导致 1,000,000,000,000/10^((3+1)*3) >= 1,并且将 i 加 1 得到 '4 '。这样,如果游戏玩的时间足够长,钱就那么高,就不会出现超过 i = 3 的问题,而是将数字封顶为“$x 万亿”
  • 堆栈溢出错误通常意味着某种“无休止”的循环。我的意思是……在您发布的代码的最后一个if 语句中……TotalMoneyText.GetComponent&lt;Text&gt;().text = "$" + TotalMoneyFloat.ToString("0.00") + " " + Numerals[i];……永远不会执行,那么它可能是检查溢出问题的候选者。换句话说,由于文本永远不会被更改并且它需要更改以结束某些循环条件,那么这将导致溢出异常。请在该行代码上放一个断点,看看它是否会被命中……我相信它永远不会被命中。

标签: c# unity3d


猜你喜欢
  • 1970-01-01
  • 2018-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-01
  • 2023-04-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多