How to use the SpriteManager?

Hi,

I’m finding it hard to find resources on how to actually use the SpriteManager in Unity. I’ve already read the forum post about it and even the wiki but I still find the instructions a bit vague.

Does anyone know how to implement or at least links to use the SpriteManager?

So far, I’ve created an empty GameObject and link the script to it but not sure what’s next. How do I set it up to play animations?

Also, I’m using a 1024 x 1024 as the atlas with 12 sprites in it. However, there’s still a bit of unused spaces in terms of width since each of my sprites are 224 x 336 pixels. Would that be a problem for SpriteManager or do I have to create the images to fit in fully inside the atlas?

Thanks in advance.

-Hakimo

If you’re not averse to spending a small amount for high quality sprite animation and management, check out the sequel to Sprite Manager… Sprite Manager 2

http://anbsoft.com/middleware/sm2/

There are examples, videos, etc available if you decide to go with it.

You will find plenty of support here for it as well.

Cheers for the reply :smile: I have seen SpriteManager 2 but I can’t spare the cash at the moment. I’m still playing around with SpriteManager. Hope I can get it to work.

-Hakimo

Check on http://www.3dbuzz.com

There is a series of tutorials on SpriteManager and Unity.

Hi and thanks for the reply.

I just watched the SpriteManager videos on 3dbuzz and it just made me even more confused. The guy made a prefab of the sprites and calls them in code. It’s different from the one I understand from the SpriteManager wiki and maybe just a bit complicated.

Also, he only loaded the sprites; He didn’t play any animations to it.

Does anyone know any default/simpler way to using SpriteManager?

Thanks

Be sure to see the sample project attached to the first post of the original SpriteManager thread. It shows how to do some simple things (though it doesn’t use the newer sprite animation capabilities).

Basically, once you’ve added the SpriteManager/LinkedSpriteManager to an empty GameObject, the next thing you need to do is add code somewhere in your game that adds a sprite to the manager. (Make sure you have a GameObject that the sprite is supposed to represent.) This is done by calling AddSprite() (see the docs on the wiki about the parameters for that method, etc) which returns a reference to the Sprite object you’ll use to do stuff to the sprite later.

After saving that Sprite reference (let’s say, to a variable named “sprite”), you’ll want to create an animation:

// Create new animation:
UVAnimation anim = new UVAnimation();

// Fill it with values:
anim.BuildUVAnim(<start>, <cell size>, <num columns>, <num rows>, <total cells>, <framerate>);

// Add the animation to the sprite:
sprite.AddAnimation(anim);

NOTE: the values in angle brackets above will need to be specified by you. And in the case of start and cell size, you’ll need to provide these values in UV-space. Since this can be cumbersome to calculate your self, have a reference to your SpriteManager object (we’ll call it “sMan” here), and call:

sMan.PixelSpaceToUVSpace( , );

or

sMan.PixelCoordToUVCoord( , );

Those convert pixel values to UV values based upon the texture that is assigned to that SpriteManager object.

I hope that helps.

Thanks very much. I should have PM you sooner to ask. Can’t believe I didn’t see a demo package for it.

I have some other questions too. In the SpriteManager.zip, there are 3 files which are the spritemanager, linkspritemanager and sprite. In the DemoPackage, there’s a SpriteClientDemo instead. Is Sprite a template for me to use or is it part of the library?

I might have some more questions but can I ask later? I’ll try and code it first :slight_smile:

Thanks again.

-Hakimo

No, the demo package uses a slightly older version when there wasn’t any animation feature and the Sprite class hadn’t been broken out into its own class yet. It shows the basics of how to add sprites (though it uses prefabs for the GameObjects to which the sprites are “attached”).

Thanks for the reply. Ah I see. There were some stuff that I wasn’t familiar with.

I managed to display a sprite at least. The problem I’m seeing right now, is that the sprite loaded is too small(is it default?) and it’s mirrored for some reason.

As for code, I created a cs file called gamemanager to handle the scripts.

using UnityEngine;
using System.Collections;

public class GameManager : MonoBehaviour {
	
	#region Fields
	
	public GameObject spritePrefab;
	public SpriteManager spriteManager;
	
	private ArrayList sprites = new ArrayList();
	
	#endregion
	
	#region Methods

	// Use this for initialization
	void Start () 
	{
		AddSMCharacter(new Vector3(0.05f, -1.2f, 0));	
	}
	
	// Update is called once per frame
	void Update ()
	{
		
	}
	
	
	private void AddSMCharacter(Vector3 position)
	{
		GameObject tempGO = (GameObject)Instantiate(spritePrefab, position, Quaternion.identity);
		spriteManager.AddSprite((GameObject)tempGO, 1f, 1f, 0, 0, 224, 336, false);
		sprites.Add(tempGO);
	}
		
	#endregion
}

For
sMan.PixelSpaceToUVSpace( <pixel width>, <pixel height> );
I’m not really sure how and where to call it? Does the values convert directly to the sprite values or do I have to print them out?

Thanks again for the help :slight_smile:

-Hakimo

The size is specified when calling AddSprite() (you’re making it 1x1 in your example call).

If it is mirrored, you may have the camera on the wrong side.

As for the PixelSpaceToUVSpace() and PixelCoordToUVCoord() calls, you call those to get your pixel-to-UV values that you’ll need when calling BuildUVAnim(). Use the “coord” version to convert the pixel coordinates of the lower-left corner of the first frame in your animation on the atlas to UV coordinates. That is the first argument to BuildUVAnim(). Use the “space” version to convert the “cell size” (second argument of BuildUVAnim()) from pixels to UV units.

But you’ll need to save the Sprite reference that is returned by AddSprite() so you can build and add an animation to it as in the example I posted earlier.

Hi, sorry to bother you again but I have some more questions I’d like to ask. I’ve manage to display the sizes I wanted although I actually found the values manually by moving the spritemanager object at runtime :stuck_out_tongue:

  1. In your DemoPackage, you have the width value as “0.524”. Did you adjusted the size manually or did you use the PixelCoordToUVCoord?

  2. In your start function, you created CreateGameObject() and CreateSprites(). What’s the difference between creating them separately instead combining them into 1? Does it have something to do with:

protected ArrayList ballSprites = new ArrayList();
	
protected ArrayList balls = new ArrayList();
  1. If you can have a look at my code below, I’m not sure how to fix the error. It says
    System.Collections.ArrayList' does not contain a definition for AddAnimation’
using UnityEngine;
using System.Collections;

public class GameManager : MonoBehaviour {
	
	#region Fields
	
	public GameObject spritePrefab;
	public SpriteManager spriteManager;
	public UVAnimation anim = new UVAnimation(); // Create Animations
	
	private ArrayList sprites = new ArrayList();
	
	private float counter;		// Used to demonstrate animation
	private Vector2 UpinUV; // UV Coordinate of the Upin Character
	private Vector2 spriteSize;// UV-space dimensions of the sprite images
	
	 

	
	#endregion
	
	#region Methods

	// Use this for initialization
	void Start () 
	{
		AddSMCharacter(new Vector3(0.02f, -1.2f, 0));	// Setting the positon of the character
	}
	
	// Update is called once per frame
	void Update ()
	{
		sprites.PlayAnim("idle"); 
	}
	
	
	private void AddSMCharacter(Vector3 position)
	{
		// Create Game Object
		GameObject tempGO = (GameObject)Instantiate(spritePrefab, position, Quaternion.identity);
		
		// Create Sprites
		spriteManager.AddSprite((GameObject)tempGO, 5f, 7.5f, 0, 336, 224, 336, false); // Setting the size of the sprite cell
		
		//// Save the actual UVs of the two soda can images (lower-left corner):
		spriteSize = spriteManager.PixelSpaceToUVSpace(0, 336);
		UpinUV = spriteManager.PixelCoordToUVCoord(224, 336); 
		
		// Fill it with values:
		anim.BuildUVAnim(spriteSize, // start
						UpinUV, // cellsize
		 				4, // columns
		  				4, // rows
		   				12, //total cells
		    			12); //fps 	
		
		sprites.AddAnimation(anim); 
		
		anim.name = "idle";  // name of animation 
		
	}
	
	#endregion
}

Thanks in advance.

-Hakim

  1. Actually, this width parameter is the “physical” size of the sprite in world space (well, local space). In other words, it’s the size of the sprite’s mesh (or at least its vertices). The “Width in pixels” you see in the comments is where the width of the image on the atlas is - and so long as you supply integers for these, it recognizes it as pixel values and does the conversion to UV space/coords for you.

  2. I just separated them to keep the sprite-specific code separate for the sake of clarity. No problem combining them.

  3. After a quick glance (forgive me if I missed an issue elsewhere in your code), the problem is you are trying to add the animation to the sprite list, which is of type ArrayList, which is just a container for other objects. Instead, you need to add the animation to individual sprites. So if you save a reference to the most recently created sprite (let’s call the reference variable “sprite”), then you would call:

sprite.AddAnimation(anim);

But it doesn’t look like you’re saving the sprite as it is returned by AddSprite(). You need to save that and add it to your “sprites” list. As it is now, it looks like the “sprites” list will be empty.

If you need to access a sprite once it has been added to an ArrayList, you’ll have to cast the list’s return type to Sprite since ArrayLists “box” objects by storing them as simple System.Object references. The way to do this is like so:

Sprite spr = (Sprite) spriteList[index];

After the above, “spr” will hold a reference to the Sprite in the ArrayList “spriteList” at the index pointed to by “index”.

If you wish to avoid this hassle, then instead of using ArrayList, add the following to your script:

using System.Collections.Generic;
...
private List<Sprite> sprites = new List<Sprite>;

With the above, you can simply access each element in the list like so:

sprites[index].AddAnimation(anim);

Also, if you use List<> or any other generic container, be sure that your Unity iPhone project is set to use .NET 2.1. To do this, click Edit->Project Settings->Player, and set “Api Compatibility level” to .NET 2.1.

:shock: My mind actually went blank for a while. I’m a bit of a noob when it comes to scripting in Unity so I apologise in advanced if my questions sound odd but:

  1. What did you mean by adding the animation to an individual sprite and how do I save a reference to recently created Sprite?

In any case, I just messed around a bit with the code and now the animation plays. The changes I made were

public Sprite sprites; //deleting the initial arraylist from before

sprites = spriteManager.AddSprite((GameObject)tempGO, 5f, 7.5f, 0, 336, 224, 336, false);
...
spriteSize = spriteManager.PixelCoordToUVCoord(0, 336);
		myUV = spriteManager.PixelSpaceToUVSpace(224, 336);
  1. The animation plays but instead of starting from the 1st frame, it started from the 2nd frame instead. The animation also starts a bit slow so I’m not sure how to make run from the start.

  2. Also, the idle animations state I’m using have lots of texture sheets/atlas to actually complete the animation sequence. How should I approach to actually load the textures in order for one animation state?

Thanks again.

  1. It looks like you’ve got it when you changed “sprites” from ArrayList to Sprite. You’re saving the return value of AddSprite() in “sprite”, which is what I was referring to.

  2. I’m not sure what to tell you on this one. Just make sure the “start” parameter to BuildUVAnim() is the lower-left pixel of the first frame of your animation in the atlas. Beyond that, I don’t know what else to recommend. As for the starting slow, it should start right away if you put your call to PlayAnim() inside of Start(). And remember that the last parameter to BuildUVAnim() is the framerate in frames per second.

  3. That’s going to be rather difficult with SM1. SM1 lacks some of the features that would help you do that, such as notifying you when the animation is finished playing so you could start another sprite’s animation to pick up where the first one left off. But basically, chaining animations from one sprite to another is the only way you’ll be able to span multiple atlases, which also means using multiple SpriteManagers since each one can only refer to one atlas. You’ll either have to figure out a way to chain them with multiple sprites, or you’ll need to reduce the size of your graphics a bit so that it can all fit onto one atlas.

  1. Thanks again for the reply. Couldn’t have made the animations work without your help.

  2. The animations played correctly and the positions seem fine. I’ve added anim.loopReverse = true; just to test things out. When the animation plays, it somehow skips the first frame but when it loops in reverse, I can see the first frame. The animation goes like this: 2,3,4,5,6,7,8,9,10,11,12 > 12,10,9,8,7,6,5,4,3,2,“1”. Not sure why it’s doing that. Am I missing something?

  3. I think I might be able to fit all the sprites in one texture sheet but I’m curious to see how chaining the animations work. What is the function “SetAnimCompleteDelegate” used for? Can it be used to notify me when the animation is finished? Also, instead of using multiple sprite sheets, is it possible to just change the order of textures within the same manager?

  4. Also, I tried attaching a touchscript(.js) to the sprite manager but that didn’t work. How do I implement a touch/click detection system for the sprite? The idea I’m trying to do is when someone clicks on the sprite, I’d want it to play/blend into another animation state.

Thanks again.

-Hakimo

  1. Yes, I think there was a bug with the loop reversing in SM1 that caused that behavior.

  2. Ahh yes, I had forgotten SM1 included animation complete delegates. Yes, you can use that to tell when an animation has finished. As for re-ordering textures, I’m not sure what you mean. A manager can only use one atlas. If you wanted to change atlases at runtime, you would have to also change all the UVs of your sprites at the same time. It’s certainly do-able, but wouldn’t make much sense unless all of your sprites needed the graphics from the second atlas at the same time. If, however, you mean reordering how a sprite uses frames from an atlas, yes, you can build an animation out of individual frames from arbitrary positions on an atlas. Instead of using BuildUVAnim(), which assumes they’re all in order in a grid, you can use an array of Vector2s which specify the lower-left coordinate of each frame (they are all assumed to be the same dimensions), then call either SetAnim() or AppendAnim().

  3. You’ll have to put your own colliders onto your GameObjects and use your own detection code for that.

Thanks again for the reply.

  1. Aww gutted, I’ll try and see how I can blend the animations without people noticing.

  2. When I meant re-ordering textures/atlases, I wanted it to work like a sorting stack. Basically, the idea is to have a stack of sheets where the animation will be stored and rotated from top to bottom. So I thought I can still use one spritemanager and change the sprite sheets/atlas at runtime. I’m imagining using arrays but not sure how to implement that in Unity. I forgot to ask, if it’s possible to change the sheets at runtime using a single sprite manager, is it still using 1 drawCall or is it a drawcall for each new sheet?

  3. For touch animation detection, I am using my own colliders

var hit : RaycastHit;

function Update () {
	
	// Use Raycast to pick objects that have mesh colliders attached.
	var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
	
	if (Input.GetMouseButtonDown (0))  //Returns true during the frame the user touches the object
	{
		if (Physics.Raycast (ray, hit, 100)) 
		{
			print("Press");
		}
	}
	
	if (Input.GetMouseButtonUp (0))  //Returns true during the frame the user deselects the object
	{
		if (Physics.Raycast (ray, hit, 100)) 
		{
			print("Release");
		}
	}
	
	else {
	}

}

It works when I create my own mesh in Unity and add a mesh collider to it. But for this case SpriteManager generates the mesh for me. I tried adding the mesh collider component in SpriteManager and my sript before running the game but that didn’t work. For some reason, it only works when I add it at runtime? :?

  1. Also I would like a second opinion about this: The main goal of my application is to have an interactive cartoon character(2D). It’ll be on the iPhone Average frames will be from 30-40 frames. The number of atlases would be around 33 sheets for behaviour states. Everytime I click on a certain area, I’d like it to play a specific animation. The transition of the animations should blend in nicely without any jittering/snapping effect. After playing around with SpriteManager, I was wondering how can SpriteManager 2 help with the development? Can it sort out the animation bug from the first SM, play animation that has more sheets etc? I’ve seen the video tutorials, and really love the interface for it but I’d like to know if it can help.

Thanks again. Appreciate the help very much.

-Hakimo

  1. Yes, you can change the texture a manager uses at runtime, but that will change the texture for all sprites managed by the manager, so just keep that in mind. And it is still just one draw call because it is still just one material (with one texture) being used.

  2. You won’t be able to use a mesh collider since the GameObjects themselves don’t have meshes with SM1. Only the SpriteManager object has a mesh. So you’ll need to use something like a box collider.

  3. SM2 can certainly help in a lot of ways. The way you would handle swapping atlases in SM2 is you would have multiple sprite objects, each tied to a different atlas, and each containing the animations that exist on that particular atlas. So let’s say “walk” and “jump” fit on one atlas. So you can use that sprite for those animations. So you create a second sprite for the “idle” and “run” animations (assuming these two fit on a single atlas). So then at runtime, if you want to play the “walk” animation, you show that sprite (either by enabling it from a disabled state, or calling sprite.Hide(false)) and play the desired animation. Then if the user wants to play the “run” animation, you hide the previous one (sprite.Hide(true)) and show the next one and play it instead. As long as the sprites on-screen are using one material, you still just use one draw call.

So it’s quite a bit easier to switch animations in a multi-atlas scenario than SM1 since in SM1 you’d also have to switch UV schemes by building a new UV animation from code for each one.

Thanks again for the reply. I finally made the decision to buy SpriteManager 2 today :smile: The first sprite manager was just too complex for me to play around with.

I’m loading the tutorial video now to see how to set it up. Although I might need your help again on how to actually use it to match the application I’m working on :slight_smile:

Also, if I have 42 sprites and I have to divide it out to 4 atlases, how do I set it up? In the inspector, I noticed the parameter “size”. Is that where I should edit it? Or do I have to write a script?

Also, you mentioned before that SM2 works well on the iPhone because of “dynamic batching”. I tried googling for it but I don’t quite understand how it works. Does it have something to do with memory management?

Thanks again.

Welcome to the family. :smile:

One note: the videos are a little out of date since SM2 has been updated and upgraded constantly. The main difference is that for PackedSprites (sprites which build your atlases for you), you’ll only use the Timeline Editor to setup the animations and static frames. But all the other settings should still be found in the inspector.

Assuming we’re talking about PackedSprites (which are by far the easiest to use), to put all of a sprite’s graphics on a particular atlas, you just select a material for it, and it will build its content to that atlas. You want to group things so that as many sprites that are visible at one time as possibly share a common material (and therefore atlas). Of course you’re limited by the iPhone’s max texture size of 1024x1024, but the more you can keep homogeneity among the sprites in terms of their materials, the fewer draw calls you’ll have and the better performance.

So let’s say you have 4 sprites: A, B, C and D. And the graphics for all of these will fit on two atlases. Now let’s say because of how your game is designed, sprites A and B will typically be on-screen together at the same time, but not usually at the same time as C and D. So you want A and B to share materials so they can batch together. So you could assign sprite A and B to “Material 1”, and sprites C and D to “Material 2”. When you build the atlases, the graphics for A and B will appear on Material 1, and C and D on Material 2.

Go to the “iPhone Guide” section of the Unity iPhone manual, and then search the page for “batching” and you’ll find a link to that topic.