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

1 Answer

1

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.