I need to have a number be divisible by certain amounts and the remainders would then by posted and I’m programming in Unity’s C# but I need a replacement since the modulus operator doesn’t seem to function on it.
Just been stung by this and I couldn’t see a recent thread with a definitive answer.
Some languages, including Python, return the mathematical mod from %.
In C# it’s rem not mod. They behave differently with negative numbers.
int rem = -8 % 32;
Debug.Log(System.String.Format("-8 % 32 = {0}", rem));
Yields:
-8 % 32 = -8
This is an important difference when wrapping array indices.
The mathematical mod is 24, not -8 and can be calculated (somewhat inconveniently) as follows:
int Mod(int a, int b)
{
return (a % b + b) % b;
}
Hope this helps someone else. I’m new to C# so if there’s a better way please post it.
O_o What? No, mod totally works.
using UnityEngine;
using System.Collections;
using System;
public class Blah : MonoBehaviour {
void Start () {
var x = 123213213;
var factor = 10;
var divs = x / factor;
var remainder = x % factor;
Debug.Log(String.Format("{0} / {1} = {2} // {0} % {1} = {3}", x, factor, divs, remainder));
}
}
Yields:
123213213 / 10 = 12321321 // 123213213 % 10 = 3
UnityEngine.Debug:Log(Object)
Blah:Start() (at Assets/Blah.cs:11)
It wont work on floats though; maybe you need to run “((int) myVector[2]) % 5” or something.
The modulus function works just fine in C#, not to mention Unityscript and Boo.
Try Mathf.Repeat
For those who are more curious, this article examines the fastest way to get the remainder between using modulus or alternative methods such as algebraic equations:
It’s obviously more for speed and micro-optimization junkies, but you’ll see several different faster ways than the straight modulus operation.
This is an old thread, but I felt compelled to write something for anybody who needs the answer to be explained and a quick example.
Short answer: Convert the int’s to var. Mod will then work.
// Wont work
int index = 3;
if(index % 2 == 0) {
}
//Will work
var indexVar = index;
var factor = 2;
if(index % factor == 0) {
}