5

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.

I.B
  • 2,925
  • 1
  • 9
  • 22
arjwolf
  • 181
  • 4
  • 16

3 Answers3

24
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)

Thomas Weller
  • 55,411
  • 20
  • 125
  • 222
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
9

Use the modulus operator, which, in simple terms, gets the remainder after division. https://msdn.microsoft.com/en-us/library/0w4e0fzs.aspx

If the remainder is 0, then you know the number is divisible by 3:

if(waveCounter % 3 == 0)
{ 
    //do something
}
Colin
  • 4,025
  • 21
  • 40
5

This problem can be solved with the modulo (or division remainder) operator as follows.

if (0 == waveCounter % 3)
{
    // do stuff
}
else
{
    // do other stuff
}
Codor
  • 17,447
  • 9
  • 29
  • 56