Sliced Sprites

As part of my Candy Bubble Drop makeover, I was told that my ‘Rainbow’ shader didnt cut it, and so I was given a pre-rendered set of sprites with the bonus text lines nicely done up.

AS TEXT REWARD

While this was really nicely done, I would need to slice it into horizontal pieces with each word saved to a separate PSD file.  Being lazy, and thinking this wouldn’t be the only time I’d want to do this, I set about creating a custom NGUI Sprite that allowed me to specify a slice height, and then a slice index, so I could chose which horizontal slice I’d display at run-time.

Creating the custom NGUI sprite class was pretty straight forward.  I added a new script to my Unity project called PBSlicedSprite.cs and added the following lines:

Screen Shot 2015-06-01 at 5.22.10 PM

I basically just overrode the normal OnFill method, and used the sliceHeight as the sprite’s height, and the sliceIndex * sliceHeight to offset the starting position.  Note, that as this is an internal class (i.e. used by me) there is no error checking on the index, so negative or large values will have curious results.

With the class created, I needed to create a custom inspector for the class as NGUI will not display public vars in one of its fancy inspectors by default.  After a little research looking at other NGUI inspectors, I came up with the following:

PBSlicedSpriteInspector.csScreen Shot 2015-06-01 at 5.25.11 PM

That inserts a line before the standard NGUI sprite panel in the inspector, allowing me to enter the slice height and the index in the editor, and adjust them in code.

I’m happy with the end result, and I’m pretty sure I’ll find a use for this class in future projects.

Let me know if you have any questions or comments.

Leave a Reply