Skip to content

Instantly share code, notes, and snippets.

@DomDomHaas
Last active August 29, 2015 14:04
Show Gist options
  • Save DomDomHaas/236d8e90b8b275b7823b to your computer and use it in GitHub Desktop.
Save DomDomHaas/236d8e90b8b275b7823b to your computer and use it in GitHub Desktop.
get a Sprite from any path using unity WWW Class (and get the mesh to add it on a meshCollider)
/// <summary>
/// Gets a sprite from any path
/// </summary>
/// <returns>The sprite from WW.</returns>
/// <param name="fullPath">Full path.</param>
public static Sprite getSpriteFromWWW (string fullPath, bool packTight = false)
{
fullPath = "file:///" + fullPath;
WWW wwwLoader = new WWW (fullPath);
//Debug.Log ("loading texture " + fullPath + " via www, loaded: " + www);
Rect rect = new Rect (0, 0, wwwLoader.texture.width, wwwLoader.texture.height);
SpriteMeshType meshType = SpriteMeshType.FullRect;
if (packTight) {
meshType = SpriteMeshType.Tight;
}
// use 100f to scale down
Sprite spr = Sprite.Create (wwwLoader.texture, rect, new Vector2 (0.5f, 0.5f), 100f, 0, meshType);
spr.name = fullPath.Substring (fullPath.LastIndexOf ("/") + 1);
return spr;
}
public static Mesh getMeshFromSprite (Sprite spr)
{
Vector2[] spriteVerts = UnityEditor.Sprites.DataUtility.GetSpriteMesh (spr, false);
ushort[] spriteIndices = UnityEditor.Sprites.DataUtility.GetSpriteIndices (spr, false);
List<Vector3> meshVerts = new List<Vector3> ();
List<int> meshIndices = new List<int> ();
foreach (Vector2 v2 in spriteVerts) {
meshVerts.Add (new Vector3 (v2.x, v2.y, 0));
}
foreach (ushort indice in spriteIndices) {
meshIndices.Add ((int)indice);
}
Mesh spriteMesh = new Mesh ();
spriteMesh.vertices = meshVerts.ToArray ();
spriteMesh.triangles = meshIndices.ToArray ();
return spriteMesh;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment