Created
May 2, 2016 06:09
-
-
Save wallrat/26539dd9b424a7835efcd2c4bf5b6bf9 to your computer and use it in GitHub Desktop.
Load a unity texture from internet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private IEnumerator FetchSprite(string imageURL) | |
{ | |
//create a www instance | |
WWW www = new WWW(imageURL); | |
//build a new texture | |
Texture2D tex = new Texture2D(1, 1, TextureFormat.ARGB32, false); | |
//set filter mode to point (pixel art) | |
tex.filterMode = FilterMode.Point; | |
//wait for www | |
yield return www; | |
//if there was no error loading sprite | |
if (string.IsNullOrEmpty(www.error)) | |
{ | |
//load the texture from www into the newly created texture2d above | |
www.LoadImageIntoTexture(tex); | |
//create an index of sprites for multi sprite | |
Sprite sprites = new Sprite[60]; | |
//the size of 1 sprite | |
int spriteWidth = 32; | |
int spriteHeight = 48; | |
//loop over 15 frames for each of 4 directions | |
for(int row=0; row<15; row++) | |
{ | |
for(int col=0; col<4; col++) | |
{ | |
//find the X position of sprite | |
int x = col * spriteWidth; | |
//find the Y position of sprite (for some reason Unity likes to use a Y position from the bottom of the image) | |
int y = tex.height - ((row + 1) * spriteHeight); | |
//sprite index | |
int idx = (row * 15) + col; | |
//create the sprite | |
sprites[idx] = Sprite.Create(tex, //sprite texture | |
new Rect(x, y, spriteWidth, spriteHeight), //bounding box of sprite | |
new Vector2(0.5f, 0f), //anchor point of sprite: bottom center | |
16f //pixels per inch | |
); | |
//name the sprite | |
sprites[idx].name = idx.ToString(); | |
} | |
} | |
} else { | |
//failed loading sprite | |
Debug.LogError(www.error + ": " + imageURL); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment