Home > Back-end >  Unity is saying my array is overflowing and crashes
Unity is saying my array is overflowing and crashes

Time:06-12

I've been trying to write a piece of code that takes a money input and rewrites it with numerals (1000 to 1 thousand, 1,000,000 to 1 million, etc.) So far, I haven't been able to get past Unity telling me that there's a stack overflow on my array before it crashes, but I don't see why it's overflowing. Am I missing something huge or is something just not right here? Unity has been giving me the error "The requested operation caused a stack overflow, MoneyTruncate() (at Assets/Scripts/Money.cs:60", which is the line pertaining to the array in this 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 && TotalMoneyFloatLimit >= 1)
        {
            TotalMoneyText.GetComponent<Text>().text = "$"   TotalMoneyFloat.ToString("0.00")   " "   Numerals[i];
        }
    }```

CodePudding user response:

What line is "line from the array"? What function is this? If I had to guess, you've got a circular reference somewhere here, which would happen if this function were called MoneyTruncate().

The logic is not doing what you think it's doing and I would urge you to set a break point and step into every function. At some point you'll see that you keep coming through the same point in your code.

I would bet this function is named MoneyTruncate and you're trying to recursively call it, but your recursion is broken - your i variable is LOCAL and any decrement before recursion is not affecting the called child/recurring instance. This means the recurring instances follow the same steps, call the same function in the same way, and this goes on until your stack builds up so many function calls that it overflows.

You're using recursion to solve a problem that doesn't really need recursion. Just check if >= 1e12 and return trillion, 1e9 for billion, etc.

  • Related