- Home /
Use for-i-loop var outside the loop
Hello, dear community. I am stuck with a trivial problem: using the value of a variable outside the loop.
Currently "i" seems to be accesible only inside the for-loop. I would like to use its value in the Update and other function.
Since I would like a variable to change every second. Is it possible?
My current script in c#:
using UnityEngine;
using System.Collections;
public class time2 : MonoBehaviour {
public int i;
void Update () {
StartCoroutine(Stopwatch());
Debug.Log ("Now i is equal to:");
Debug.Log (i);
}
IEnumerator Stopwatch(){
for (int i = 0; i < 10; i++){
yield return new WaitForSeconds(1);
}
}
}
Answer by jpthek9 · Oct 06, 2014 at 12:52 PM
using UnityEngine;
using System.Collections;
public class time2 : MonoBehaviour {
public int i;
void Update () {
StartCoroutine(Stopwatch());
}
IEnumerator Stopwatch(){
for (i = 10; i < 20; i++){
yield return new WaitForSeconds(1);
Debug.Log (i);
}
}
}
jpthek9, thank you very much!!! It worked!!!
dmg0600, Bunny83, jpthek9, thank you all. I apreciate your help and how quickly you were able to explain me where I was wrong.
The main thing was that before, you were doing Debug.log(i) outside of the Coroutine. The value gets changed in the Coroutine so you have to Log in the Coroutine with the same time intervals. Otherwise, you'll just get a flurry of Logs.
Answer by dmg0600 · Oct 06, 2014 at 12:01 PM
using UnityEngine;
using System.Collections;
public class time2 : MonoBehaviour {
public int i;
void Update () {
StartCoroutine(Stopwatch());
Debug.Log ("Now i is equal to:");
Debug.Log (i);
}
IEnumerator Stopwatch(){
for (i = 0; i < 10; i++){
yield return new WaitForSeconds(1);
}
}
}
Removing the int declaration of the for loop it will use the class variable instead of its own local variable. This way you can see its value outside the loop.
dmg0600, thank you for your promt answer!
Unfortunately, I failed to make it work. $$anonymous$$y program still counts "i" as initial declared value.
I want it to show: 10 11 12 13 14 15 16 17 18 19
but what I get is only 10.
Here is the code:
using UnityEngine;
using System.Collections;
public class time2 : $$anonymous$$onoBehaviour {
public int i;
void Update () {
StartCoroutine(Stopwatch());
Debug.Log (i + 10);
}
IEnumerator Stopwatch(){
for (i = 0; i < 10; i++){
yield return new WaitForSeconds(1);
}
}
}
@Fewpwew130: First of all, plesae don't post replies as answer. Answers should answer the question. I converted your answer into a comment.
Your problem is that you start a new coroutine every frame. Since non of the coroutines can ever exit (since all use the same variable "i") you end up with tons of coroutines running at the same time.
You should start your coroutine just once in Start. It runs automatically in the background.
@dmg0600: You might want to change your answer since you're doing the same in your answer and it doesn't make much sense that way...