Yield WaitForSeconds Javascript to C# Problem

I can’t get these few lines to work correctly in C#. Any help would be great, here is the segment.

function UpdateRandom ()
{
	while(true)
	{
		randomPush = Random.insideUnitSphere * randomForce;
		yield WaitForSeconds(randomFreq + Random.Range(-randomFreq / 2, randomFreq / 2));
	}	
}

And yes, I know it cannot return a void in C#. Anyways, thanks for taking a look!

Actually you can return void in C#, that’s not the problem

Your problem is that in C# you cannot just yield from a normal function block. You have to yield out of an IEnumerator function and call it from StartCoRoutine

the short answer is this:

public IEnumerator UpdateRandom()
{
    while(true)
    {
        randomPush= Random.insideUnitSphere*randomForce;
        yield new WaitForSeconds(randomFreq + Random.Range(-randomFreq / 2, randomFreq / 2));
    }
}

With that said though, I have no clue what you’re doing here and I don’t think you’re using random correctly.

public IEnumerator UpdateRandom ()
{
while(true)
{
randomPush = Random.insideUnitSphere * randomForce;
yield return new WaitForSeconds(randomFreq + Random.Range(-randomFreq / 2f, randomFreq / 2f));
}
}

The syntax is wrong in a few places

Functions in C# begin with the return type and to use a coroutine the function must return a IEnumerator

The correct syntax would for the function declaration would be

IEnumerator UpdateRandom()

And the correct syntax for the yield is

yield return new WaitForSeconds(blahblah)

The scripting reference provides a quick way to check how to do things between the languages, there’s an option in the top left to change what language you’re viewing the reference in, so just flip between javascript and c# to see the difference.

Assuming randomPush is declared elsewhere, this should be all the changes

IEnumerator UpdateRandom ()
{
    while(true)
    {
       
       randomPush = Random.insideUnitSphere * randomForce;
       yield return new WaitForSeconds(randomFreq + Random.Range(-randomFreq / 2, randomFreq / 2));
    }  
}