- Home /
Float to int casting in C# script with modulo giving division by zero error
I'm following this tutorial on using offsetting to animate a sprite sheet, which was going fine until I had to add controls for fps. The lesson is in JS, but I need to learn in C#. Unlike the example in the video, I have to explicitly cast the (Time.time * fps) from float to int, but no matter which method I try, it throws up a division by zero error on the line with the modulo. This makes little sense since print(frameNumber) shows nothing but integers. Does anyone know what's going on? I've been searching and searching, but can't find any answers
This is my code:
public int columns; // frames along x
public int rows; // y
public int fps = 8; // frames per sec
void Update ()
{
int frameNumber = Time.time * fps; // Need to cast float to int here, but it causes error
print (frameNumber);
frameNumber = frameNumber % (columns * rows); // ex. 1 % 16 = 1, 17 % 16 = 1. dividend = quotient * divisor + remainder, 1 = 0 * 16 + 1, 17 = 1 * 16 + 1.
Vector2 size = new Vector2 (1.0f / columns, 1.0f / rows); // ex. sheet has 16 frames across, scale texture to 1/16 width
Vector2 offset = new Vector2 (frameNumber * size.x, rows); // ex. (1 * 1/16, 1)
renderer.material.mainTextureOffset = offset; // offsets texture to other "frames"
renderer.material.mainTextureScale = size; // scale texture to proper size
Answer by Loius · Apr 08, 2013 at 02:40 AM
columns * rows is zero
% does actually perform a division operation, you can't pass zero into it
Ah, I just figured it out and it was caused by a completely different set of zeros than I expected. I forgot that the variables for columns and rows needed to be filled in in the Inspector or else they turn up zeros.
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
C# getComponent result error cast 3 Answers
Floating Point and ToString issue 2 Answers
What is wrong with my throttle script? 2 Answers