Second for loop isn't running inside my update - c#

This if statement within the update() have 2 for-loop, but it only runs the first one after the if condition is activated, and I don't know why.
I'm building a code for path optimizing in unity. Currently I have to find out the path that came across the nodes/points/positions with a certain positions array that the index is the order the path should follow. Some path between 2 nodes are repeated , ex: A to B and B to A is consider the same path and shall thicken the width of line AB eventually rendered. So I tried to sort out the position array into 2 different array for comparing if any of the pair of nodes(or we can say line) is repeated. And I encountered a problem in if statement within the update().
The first should sort out the original array for later comparison. The second one is just for testing if the first one do their job. No comparing yet. However after hitting play and satisfy the if statement I can see all the Debug.log in the first one, everything is normal, the sorting is normal, while the second one just doesn't print anything at all.
I tried comment out the first one, and the second one will run.
I tried to put second one outside the if statement, after it, and without commenting the first one, the second one won't run.
I tried to put the second one before the first one, in the if statement, the second one will run and the first one won't.
So I think this might be some kind of syntax error or am I using the if statement wrong? Please help.
if (l > 0)//activate when we choose any preset processes
{
for (int n = 0; n <= positions.Length; n++)//this loop will sort all the pos1 and pos 2 into array for current frame
{
curPos_1 = positions[n];//current position of node 1
curPos_2 = positions[n + 1];
Debug.Log("CURPOS_1 of line number " + n + " is " + curPos_1);
Debug.Log("CURPOS_2 of line number " + n + " is " + curPos_2);
flag[n] = 0;
Pos_1[n] = curPos_1;
Pos_2[n] = curPos_2;
Debug.Log("POS_1 array of line number " + n + " is " + Pos_1[n]);
Debug.Log("POS_2 array of line number " + n + " is " + Pos_2[n]);
}
for (int o = 0; o <= positions.Length; o++)
{
Debug.Log("flag of number " + o + " is " + flag[o]);
}
}
As described, all for loop should print something. Not just one of it.

Have you checked your Unity Console Window ?
In your first loop you get the next item but its condition will fail at the end, i.e. off by one.
Correct code should be something like this:
var floats = new float[100];
for (var i = 0; i < floats.Length - 1; i++)
{
var f1 = floats[i];
var f2 = floats[i + 1];
}
Now, Unity, has a behavior of ON ERROR RESUME NEXT, so it's highly probable that an error has occured but you haven't seen it (did you turn off the red icon for toggling errors in console ?).
Also, for some conditions only you know about (you didn't post the whole context), it could work once after you've changed some state of your program.

Related

Unity is saying my array is overflowing and crashes

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];
}
}```
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.

learning C#, need help understanding this code

I am learning C# and I came to this "for" function and something really bothers me about it:
int[] arrayNumbers = new int[numberAmmount];
// take "numberAmmount" as 5 so numberAmmount = 5;
for (int i = 0; i < numberAmmount; i++)
{
Console.Write("{0} Number: ", i + 1);
numberAmmount[i] = int.Parse(Console.ReadLine());
}
Isn't "i++" in for function the same i as in the Console.Write "i + 1"
Shouldn't i after the first cycle be 2?
and after the second cycle be 4 because of the i + 1 in console.write???
Basically I am trying to get in a number from the user which will be the amount of numberAmmount and by this for function i give every numberAmmount[x] a value and then have my program decide the highest and the lowest number but I don't understand why the i + 1 doesn't add an extra 1
edit: got it thanks
The syntax i + 1 does not have an assignment operator. That code is printing the value of i plus a constant. So when your loop is looping from 0...n Console.write is printing the counting value of each loop 1...n+1.

Fetching Directory Count

I need a little help with a little project I'm working on in C#.
Here is my code:
//TO FETCH DIRECTORY TEST
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(#"C:\Users\Tahmid\Downloads");
int count = dir.GetFiles().Length;
Simply what I want it to do is see how many files is in my "Downloads" folder.
I ran into 2 problems though.
First problem is the word System is underlined in green and it says "Unreachable Code Detected".
At first I thought It might be caused by a namespace I'm missing, I checked back at my code and saw I already have using System.IO; and using System;. I think these 2 are the one's I need for the directory count.
So I am out of idea's on why its underlined green. xD
Second problem is that when I put those 2 lines of code into my project it breaks another section of my code which is this:
case "switch window":
SendKeys.Send("%{TAB " + count + "}");
count += 1;
break;
I get "count" underlined in blue saying "Use of unassigned local variable 'count'"
I'm quite baffled at the fact why the 2 lines of code to fetch the directory length break that.
We need to see more of your code to know the answers for sure... but here are some ideas that might help.
This would cause the first error
if (false)
{
// this code is unreachable... false will never be true.
//TO FETCH DIRECTORY TEST
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(#"C:\Users\Tahmid\Downloads");
int count = dir.GetFiles().Length;
}
The second error is because you are using count before initializing it ... something like this:
int count;
/// ... more code
case "switch window":
SendKeys.Send("%{TAB " + count + "}"); // uninitialized use.
count += 1;
break;
Where you need this:
int count;
count = 0; // now count has a value.
/// ... more code
case "switch window":
SendKeys.Send("%{TAB " + count.ToString() + "}");
count += 1;
break;
The 2nd being caused by the first is clear -- if the code is never reachable then it will never set count to a value so count is initialized.

Outlook.Items Restrict() weird behavior

I just want to filter my Mails with the Restrict-Method like so:
restriction += "[ReceivedTime] < '" + ((DateTime)time).ToString("yyyy-MM-dd HH:mm") + "'";
var count = oFolder.Items.Restrict(restriction).Count;//Cast<object>().ToList();
for (int i = 0; i < count; i++)
{
var crntReceivedTime = ((OutLook.MailItem)oFolder.Items.Restrict(restriction).Cast<object>().ToList()[i]).ReceivedTime;
if (crntReceivedTime > time)
{
string t = "";
}
}
Theoretically the line string t = ""; should never be called, because I determined the Items to never have entries which ReceivedTime's value is bigger than time.
The problem is the line gets called, what means the restricted Items Collection contains entries which its shouldn't contain.
Did I do something wrong or is the Restrict()-method just failing?
Firstly, you are using multiple dot notation. You are calling Restrict (which is expensive even if it is called once) on each step of the loop. Call it once, cache the returned (restricted) Items collection, then loop over the items in that collection.
Secondly, what is the full restriction? You are using += to add an extra restriction on ReceivedTime. What is the actual value of the restriction variable?
Edit: I had no problem with the following script executed from OutlookSpy (I am its author - click Script button, paste the script, click Run):
restriction = " [ReceivedTime] < '2011-06-11 00:00' "
set Folder = Application.ActiveExplorer.CurrentFolder
set restrItems = Folder.Items.Restrict(restriction)
for each item in restrItems
if TypeName(item) = "MailItem" Then
Debug.Print item.ReceivedTime & " - " & item.Subject
End If
next

Print index from array

I am working on a text-based game, and I want to print the results in the end.
However, at the moment it only prints the latest input data and not the 5 loops in the array.
This is my array
int[] turnarr = new int[5];
turnarr[x] = turn;
for (int i = 0; i < turnarr.Length; i++)
Console.WriteLine(turnarr[i] + "\t" );
It's hard to be certain, as I only see part of the code, but I suspect that you are recreating the turnarr array in each turn, which would make every entry except the last one zero.
If the value of x never changes then you're only writing to a single item in the array, and thus overwriting it every time with the latest value of turn.
If turn is your last turn value, and x is 4, you will see four zeroes on their own lines and then the value of turn because you are only assigning to the xth index of turnarr
I took a look at your pastebin and tracked the issue down I believe:
The following line:
Console.WriteLine(turnarr[i] + "\t" + windarr[i] + " ms \t" + apmeterarr[x] + "m\t\t" + lenghtarr[x] + " meter\t\t");
you are using i for 2 spots, and x for the other 2 for your index variable...
Change
apmeterarr[x] and
lenghtarr[x]
To
apmeterarr[i] and
lenghtarr[i]

Categories

Resources