Loading sprites from external files

I started programming in Unity3D with the beta of version 4.6. One of the first things that I wanted to do, with my test game, was to load an external image file and put it on a UI button.

The new UI from version 4.6 uses sprites for images, not textures. So, to load an external image into an UI control, you need to create a sprite through code. It’s work only with local images. The code is in C#, and you need to include using System.IO;

This piece of code was taken from  my first game, a Memory game. This code does:

Texture2D tex = null;
byte[] fileData;

sPath = Application.dataPath + "/externalsets/";
string sName = sPath + sFileName + ".jpg";

if (File.Exists(sName)){
  fileData = File.ReadAllBytes(sName);
  tex = new Texture2D(2,2);
  tex.LoadImage(fileData);

  newImg = Sprite.Create(tex,new Rect(0,0,tex.width,tex.height),new Vector2(0.5f,0.5f));
}

– Create an empty 2D texture

– Create an array of bytes

– Generate the file name from the application path (in design the assets folder, in the compiled the game_data folder). sFileName was passed as parameter for the function.

– Check if the desired file exist, tem load all the bytes into the bytes array.

– Create the new texture with the size 2×2. The size here doesn’t matter, because when loading the bytes inti the texture it will be resized to the size of the loaded image.

– Load the bytes of the image into the texture, with the LoadImage method of 2DTexture class.

– Create a sprite with the method Create from the Sprite class. The parameters for this method are the texture, the Rect with the final size of the sprite, and the pivot.

For more information on the parameters of the methods, see the Unity documentation.

About the Author: Dark Elf

Leave A Reply

Your email address will not be published. Required fields are marked *