Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On every third iteration C# [duplicate]

Tags:

c#

loops

I have this loop which is performing a simple task for me every time my variable is a multiple of 3, currently I have to create a big loop which contains every multiple of 3 with a logical OR (3, 6, 9, ...). I am wondering if there is a more efficient way of doing this.

This is my code snippet:

if (waveCounter == 3 || waveCounter == 6 || waveCounter == 9 || waveCounter == 12)
{
    amount = 0.03f;
    dayNight.lightAmout = amount;
    dayNight.light.intensity = Mathf.Lerp(dayNight.light.intensity, dayNight.lightAmout, fadeTime * Time.deltaTime);
}
else
{
   amount = 1f;
   dayNight.lightAmout = amount;
   dayNight.light.intensity = Mathf.Lerp(dayNight.light.intensity, dayNight.lightAmout, fadeTime * Time.deltaTime);
}

My objective here is to get rid of writing those multiples of 3 in the if statement and still achieving the same goal every time my waveCounter variable is the next multiple of 3.

like image 396
arjwolf Avatar asked Apr 07 '17 14:04

arjwolf


1 Answers

if((waveCounter % 3) == 0)

Modulo arithmetic: it divides a number by 3 and checks for the remainder. A number that is divisable by 3 has no remainder (and thus ==0)

like image 162
Marc Gravell Avatar answered Oct 16 '22 03:10

Marc Gravell