- Home /
Loop a function in c#.HELP!!!
I want to when i will press "Buy Dealer" button,function Deal will loop.Every 3 seconds Deal function need to add +20$ and -1g meth...
...So,when i apply this script unity is crashing...How to loop a function,please help and sorry for my broken english.
function Update()
{
if(dealers >=1)
{
if(methScript.meth >=1)
{
while(true)
{
Deal();
}
}
}
}
IEnumerator time()
{
yield return new WaitForSeconds(3f);
}
void Deal()
{
moneyScript.money +=20;
methScript.meth -=1;
StartCoroutine(time());
}
You're using your coroutine wrong - only the time() function waits for 3 seconds before it re-commences - your Update() function will still get called thousands of times. This then starts another co-routine - and so you're running out of stack space, hence why unity is crashing.
Here is a unity tutorial about loops http://unity3d.com/learn/tutorials/modules/beginner/scripting/loops which is part of a larger series that you should probably learn http://unity3d.com/learn/tutorials/modules/beginner/scripting
The reason unit is crashing is because you have an infinite loop, while(true). As a result, your program will repeatedly evaluate the condition and inside of the loop forever, without any breaks to update the display or unity itself.
Answer by _joe_ · Apr 02, 2015 at 09:22 PM
Careful, you're mixing C# and JS in your code... It's always best to use Coroutines instead of Update, so I wrote the basic coroutine, add your conditions and you'll be set.
Here you go:
void Start () {
StartCoroutine("Deal");
}
IEnumerator Deal(){
while(true){
moneyScript.money +=20;
methScript.meth -=1;
yield return new WaitForSeconds(3);
}
}
yes it works,but i need loop this coroutine when i will press Buy Dealer button,not from the start.
Answer by UNZoOM · Apr 02, 2015 at 09:23 PM
function Update()
{
if(dealers >=1)
{
if(methScript.meth >=1)
{
while(true)
{
InvokeRepeating("Deal",0,3);
}
}
}
}
function Deal()
{
moneyScript.money +=20;
methScript.meth -=1;
}
@UNZoO$$anonymous$$: You have the same infinity loop which never exits and isn't part of a coroutine (contains at least 1 yield statement) as the OP. So you're trapped inside the while loop "forever".