Animating Sprites Not working in C#

Hi All

I have downloaded the java script from the unity forum for animating sprites

#pragma strict

var uvX = 4; 
var uvY = 2;
var fps = 24.0;
function Update () {

    var index : int = Time.time * fps;

    index = index % (uvX * uvY);

    var size = Vector2 (1.0 / uvX, 1.0 / uvY);

    var uIndex = index % uvX;
    var vIndex = index / uvX;
     var offset = Vector2 (uIndex * size.x, 1.0 - size.y - vIndex * size.y);
    GetComponent.<Renderer>().material.SetTextureOffset ("_MainTex", offset);
    GetComponent.<Renderer>().material.SetTextureScale ("_MainTex", size);
}

but when i converted into C#

using UnityEngine;
using System.Collections;

public class AnimationSS : MonoBehaviour {

    // Use this for initialization

    public float uvAnimationTileX = 4;
    public float uvAnimationTileY = 2;
       
    public float framesPerSecond = 24.0f;
       
        void Update () {
           
            // Calculate index
            float index = Time.time * framesPerSecond;
            // repeat when exhausting all frames
            index = index % (uvAnimationTileX * uvAnimationTileY);
           
            // Size of every tile
            Vector2 size =new  Vector2 (1.0f / uvAnimationTileX, 1.0f / uvAnimationTileY);
           
            // split into horizontal and vertical index
            float uIndex = index % uvAnimationTileX;
            float  vIndex = index / uvAnimationTileX;
           
            // build offset
            // v coordinate is the bottom of the image in opengl so we need to invert.
            Vector2 offset = new Vector2 (uIndex * size.x, 1.0f - size.y - vIndex * size.y);
           
            GetComponent<Renderer>().material.SetTextureOffset ("_MainTex", offset);
            GetComponent<Renderer>().material.SetTextureScale ("_MainTex", size);

}

}

The C# coding is working. But the output is highly difference in js coding. I dont know what i am making mistake… I want the same output as the js file. Could any one help me… What i have done wrong in C# file…

Thanks in Advance

One possible difference: JS will make uvx and uvy int’s, while you have them declared as floats. This is probably affecting the mod and division math.

Out of curiosity, is there any particular reason you’re using this as opposed to SpriteRenderer and Sprites? It looks to me like you googled, found some very old code, and used it, but the Sprite system is a relatively recent addition to the engine and will handle this sort of thing much better.

Hi Star Manta

Thanks for you reply. I think you are correct…

i have googled the above code and found in the unity forum…To get the js output in C#. What i have to Do…

you have mentioned…

Where i will get the example code for the sprite render …in the recent addition engine code…

Just change “float” to “int”.

https://www.youtube.com/watch?v=gbgIA3pwpHc