Accessing variables from a for loop
Hi! I was thinking on is it possible to access variables inside the for loop to use them outside the loop. For example access the int i outside the loop.
Yes you just have to declare it outside of it
int i =0;
for(i=0;i < somenumber; i++){
if(condition)break;
}
Debug.Log("iteration = " +i);
you should explain more your situation and what you are trying to do and why to get further/better help.
Answer by Bob-The-Zealot · Aug 31, 2015 at 10:18 AM
Yes, if you define the variable in the main scope, then you can use it anywhere in the main scope.
You can choose to use a for loop or a while loop.
For loop:
int i;
for (i = 0; i < somenumber; i++) {
// whatever you put in your loop
}
While loop:
int i = 0;
while (i < somenumber) {
// whatever you put in your loop
}
You can access int i
anywhere inside whichever function you defined int i
in: Debug.Log ("int i = " + i);
Learn more about scope here.
Your answer
![](https://koobas.hobune.stream/wayback/20220612002101im_/https://answers.unity.com/themes/thub/images/avi.jpg)