Loading Custom Sprites

While the code for setting up items and guns have a plethora of helper methods to set up their sprites and animations in only a few lines of code, there will come times where it may be necessary to load sprites yourself.

Sprite Collection Recap

For a more thorough explanation of the tk2dSprite component and Sprite Collections, see; Setting Sprites

To recap information covered on other pages, every gameObject with a sprite has a component called tk2dSprite which handles the rendering of its texture. Every texture exists within a 'sprite collection', and the tk2dSprite must be set to the correct collection in order to render a specific sprite.

When it comes to adding new sprites to the game, therefore, we must either create a new sprite collection, or add our new sprite to an existing collection.

Adding an Embedded PNG

If you are not using Unity Asset Bundles in your project, you will need to load embedded PNGs from your project. This is fairly simple, and several helper methods exist in Alexandria's ItemAPI to assist you. Here, we will be using the method AddSpriteToCollection in Alexandria's SpriteBuilder class.

//The resource path of the embedded texture in your project files (Make sure to embed your texture as if it were an item sprite)
//The resource path should be formatted as "Namespace / Folders / Texture Name". In the below example, you can see the path to a texture called example_texture_001, in the folder Effects, which itself is in the folder Resources. All of this is in the hypothetical namespace MyNameSpace.
string resourcePath = "MyNameSpace/Resources/Effects/example_texture_001";

//The collection we will be adding a sprite to. This can, in theory, be any sprite collection, however most modded content adds to the itemCollection, which is easily accessible in Alexandria's SpriteBuilder class.
tk2dSpriteCollectionData collection = SpriteBuilder.itemCollection;

//The string id we want for the texture after it's added
string name = "example_texture_001";

//We provide all the above examples to the AddSpriteToCollection method to package our embedded texture into the existing itemCollection. 
int addedSpriteID = SpriteBuilder.AddSpriteToCollection(resourcePath, collection, name);
//This returns the integer Id of the added sprite in the collection, which you could choose to save if you need to use it later, or just ignore.

Once the sprite is correctly packaged into a collection, you can follow the steps outlined in Setting Sprites to set the sprite of a GameObject to your new texture.

Loading from an Asset Bundle

Last updated

Was this helpful?