- Home /
Increment variable over time
hi. I have this small problem to do some automatic update on a guitext. what i want to do is, to update a guitext after 3 seconds constantly until the game finish. the value would be incrementing one by one after 3 seconds.
Class guitextautoupdate{ private int _i; System.Collections.IEnumerator yieldConnect() { _i++; Guitext.text = _i.ToString(); yield return new WaitForSeconds(3); }
void Start()
{
StartCoroutine(yieldConnect( ));
}
}
What i think is, this code will update the text after 3 seconds. but it doesnt do it.
so how do i do that?
Answer by Eric5h5 · Jun 25, 2010 at 01:56 AM
I generally find InvokeRepeating best for this sort of thing.
private int _i = 0; void YieldConnect() { guiText.text = (++_i).ToString(); }
void Start() { InvokeRepeating ("YieldConnect", 3.0f, 3.0f); }
Use CancelInvoke
to make it stop. Note that the correct spelling is guiText
, not Guitext
.
Answer by Mike 3 · Jun 25, 2010 at 01:35 AM
Something like this should do it:
Class guitextautoupdate{ private int _i; System.Collections.IEnumerator yieldConnect() { while(true) { _i++; Guitext.text = _i.ToString(); yield return new WaitForSeconds(3); } }
void Start()
{
StartCoroutine(yieldConnect( ));
}
}
I did this, but it still doesnt do it. do you think i have to put it inside an update method?
definitely not, no. are you sure Guitext.text is right there? Guitext isn't declared, and isn't the normal way to access a GUI Text object
sorry $$anonymous$$ike. your post is actually works. I dont know why, i use a function to execute on those coroutine, and it just never go to the next loop. but anyway, we have 2 solutions.
Answer by Bob 3 · Nov 25, 2010 at 04:58 AM
How can one do this in javascript for Unity? I've tried, but as a novice coder, translating c# to JS is a little out of my league somewhat. Thanks.
This isn't an answer...ask this as a new question. I'd answer here anyway, but I can't post formatted code in a comment.
Answer by qJake · Jun 25, 2010 at 01:36 AM
You just need to make your coroutine have a while loop if you want it to go forever:
IEnumerator yieldConnect()
{
while(true)
{
// your code
yield return new WaitForSeconds(3);
}
}
You can also use a condition, like while(i < 10)
or something like that. You can also break out of the while loop (and thus, end the coroutine), with the break;
keyword.