I’m building a 2D sprite based game in Unity. I’m aware of SpriteManager and SpriteManager2, but they seem unnecessary for my needs in light of Unity’s dynamic batching. I’ve created a Sprite Class that steps through a shared material to simulate animation, and have got the batching to work just fine. However, when I do this all the instances of the Sprite are always on the same ‘frame’ so to speak. I have discovered I can fix this by using renderer.material calls instead of renderer.sharedMaterial calls, but of course this prevents the Sprites from batching.
Below is the code for my Sprite animation which is modified off the TiledAnimation on the Unity wiki.
This code lets the sprites batch, but does not let separate instances display different frames… any help is appreciated.
(C#)
//uvAnimationTileX = number of columns of animation
//uvAnimationTileY = number of rows of animation
//frameSpeed = time in seconds between each frame change
//time = count down timer for frame changes
//minIndex = starting frame for animation
//maxIndex = ending frame for animation
//infinitePlay = should the animation loop infinitely
//numPlays = how many times the animation has looped
//playCount = how many times the animation should loop.
public void Update()
{
time -= Time.deltaTime;
if (time <= 0)
{
index++;
if (index > maxIndex)
{
index = minIndex;
numPlays++;
}
if (infinitePlay || numPlays < playCount)
{
// 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);
renderer.sharedMaterial.SetTextureOffset("_MainTex", offset);
renderer.sharedMaterial.SetTextureScale("_MainTex", size);
time = frameSpeed;
}
else
{
if(RepeatEnd != null)
RepeatEnd(this); //Event that is fired when the animation has played all the times its allowed.
}
}
}
Edit - First post on these forums. I tried to find a previous thread that addressed this issue, but if I missed an obvious one I apologize.