Search code examples
imageunity-game-enginebitmapdrawingsprite

How do you create images programmatically, for use with 2D sprites in Unity?


I want to be able to programmatically create player sprites in Unity. I have two specific use cases in mind for this:

  1. I want to create characters using 'building blocks', i.e. a separate head, body and legs, but I don't want to stress the processor by compositing every shot so I want to generate a programmatic 'sprite sheet' that is cached in memory. This allows for the creation of a simple customisation system, with clothing, hairstyles etc.

  2. I want certain colours (i.e. skin, clothing and so on) to be user-selectable.

Now, I don't think I need an exact solution to these as I can work them out myself. I just need a decent reference that shows how to programmatically read and write pixel colour values from resources, create images, and convert the resulting images into 2D sprites.

Can someone point me in the right direction? Every time I google for it, I just get beginner's guides about how to swap between two pre-drawn sprites.


Solution

  • To create an image programmatically, you can create a new Texture2D instance, then call Texture2D.SetPixel repeatedly, or use SetPixels, SetPixels32, or SetPixelData so you don't have to call SetPixel thousands of times.

    If you want to use it with SpriteRenderer, you will need to use Sprite.Create with your custom texture, then set SpriteRenderer.sprite to it.

    You can multiply colours: myPixelColor * Color.red will multiply the blue and green channels by zero and the red channel by 1, resulting in a pixel somewhere between black and red.

    That said, drawing all the parts of your character as separate sprite objects may not be as expensive as you think, and SpriteRenderer comes with a colour filtering property. I don't know your exact situation.