How to allow players to import sprite sheets into game build?

Hello! So I’ve tried Googling to see if anybody else has asked this same question, and have unfortunately I had no luck in finding similar situations, so I thought I should be the one to ask! :slight_smile:

I’ve been working on a top-down 2D Unity project for a few months, and eventually I’m soon going to start working on the character select system of the game. All characters will have the same abilities so it’s only just going to be graphical changes between each character.

When it comes to the character system, I would like to allow players to be able to add their own characters into the game using their own created sprites (Preferably I’d like to allow players to do this through a singular sprite sheet to make things more simple, although if this can only be achieved through other means instead, then I’ll take whatever answer I can get. :slight_smile: ) Is there supposedly anyway to allow players to import their own sprites into a Unity build?

If anything I said is confusing to understand, I will try my best to reword things. Thank you for reading, I look forward to everybody’s answers!

If the game is on WIndows you can use File.ReadAllBytes to read any file in any folder you specify. Then you can load the texture using Texture2D.Load, and you can then create any sprites from it using Sprite.Create.

Here’s some example code, I made up random values like the file path, expected texture size and sprite positions to help you get a better idea:

string folderPath = Application.persistentDataPath;
if (!Directory.Exists(folderPath)
{
    return;
}

string filePath = Path.Combine(folderPath, "custom_texture.png");
if (!File.Exists(filePath))
{
    return;
}

byte[] imageData = File.ReadAllBytes(filePath);
Texture2D texture = new(2, 2);
if (!texture.LoadImage(imageData))
{
    return;
}

const int ExpectedWidth = 1024;
const int ExpectedHeight = 512;
if (texture.width != ExpectedWidth || texture.height != ExpectedHeight)
{
    return;
}

Sprite[] sprites = new Sprite[2];
Vector2 spritePivot = new(0.5f, 0.5f);
sprites[0] = Sprite.Create(texture, new(0, 0, 512, 512), spritePivot);
sprites[1] = Sprite.Create(texture, new(512, 0, 512, 512), spritePivot);

Yes! My game is on WIndows, thank you for your answer! I shall get back to you when I’ve tried out this solution. :slight_smile:

ImageConversion.LoadImage is the recommended way to do so.

Also very important: try/catch any IO operation! These might fail for any number of reasons especially if you let users choose to load certain files. Ie the file may be open and locked by an image editing program, or in a folder where the user doesn’t have permission to read/write, and so forth.

I am back to tell you this appears to work well. This answer helps me out a lot, thank you very much!

I will bare this in mind, thank you too for this clarification CodeSmile :slight_smile: