Skip to content

Instantly share code, notes, and snippets.

@FVSHaLuan
Last active August 29, 2015 14:27
Show Gist options
  • Save FVSHaLuan/de85dbc72b9f3716ff33 to your computer and use it in GitHub Desktop.
Save FVSHaLuan/de85dbc72b9f3716ff33 to your computer and use it in GitHub Desktop.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
/* by FVS - HaLuan */
/// <summary>
/// Run:
/// 1. Add this script to a GameObject
/// 2. Have an internet connection
/// 3. Play
/// 4. Watch Inspector window for result
/// 5. After the Atlas showed up, change Show Sprite Index value to see difference
/// </summary>
public class TexturePackingOnDemand : MonoBehaviour
{
string[] imageSources =
{
"https://upload.wikimedia.org/wikipedia/en/thumb/0/02/Homer_Simpson_2006.png/212px-Homer_Simpson_2006.png",
"https://upload.wikimedia.org/wikipedia/en/0/0b/Marge_Simpson.png",
"https://upload.wikimedia.org/wikipedia/en/a/aa/Bart_Simpson_200px.png",
"https://upload.wikimedia.org/wikipedia/en/9/9d/Maggie_Simpson.png",
"https://upload.wikimedia.org/wikipedia/en/e/ec/Lisa_Simpson.png"
};
[SerializeField]
List<Texture2D> textures = new List<Texture2D>();
[SerializeField]
Texture2D atlas;
[SerializeField]
int showSpriteIndex = 0;
Rect[] spriteRects;
SpriteRenderer spriteRenderer;
// Use this for initialization
IEnumerator Start()
{
// Load texture
for (int i = 0; i < imageSources.Length; i++)
{
///
WWW www = new WWW(imageSources[i]);
while (!www.isDone)
{
yield return null;
}
///
if (www.texture != null)
{
textures.Add(www.texture);
Debug.Log(i + " texture(s) loaded");
}
}
// Pack
atlas = new Texture2D(2048, 2048);
spriteRects = atlas.PackTextures(textures.ToArray(), 2);
// Add Sprite render component
spriteRenderer = GetComponent<SpriteRenderer>();
if (spriteRenderer == null)
{
spriteRenderer = gameObject.AddComponent(typeof(SpriteRenderer)) as SpriteRenderer;
}
///
yield return null;
}
// Update is called once per frame
void Update()
{
if ((atlas != null) && (showSpriteIndex < spriteRects.Length) && (showSpriteIndex >= 0))
{
Vector2 position = new Vector2(spriteRects[showSpriteIndex].xMin * atlas.width, spriteRects[showSpriteIndex].yMin * atlas.height);
Vector2 size = new Vector2(spriteRects[showSpriteIndex].width * atlas.width, spriteRects[showSpriteIndex].height * atlas.height);
spriteRenderer.sprite = Sprite.Create(atlas, new Rect(position, size), Vector2.zero);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment