Skip to content

Instantly share code, notes, and snippets.

@grimmdev
Created June 18, 2014 00:56
Show Gist options
  • Save grimmdev/0a4d63f5d45f0b90dc52 to your computer and use it in GitHub Desktop.
Save grimmdev/0a4d63f5d45f0b90dc52 to your computer and use it in GitHub Desktop.
Load Sprite Dynamically from URL using C#
// yay! using statements!
using UnityEngine;
using System.Collections;
// this is pish posh class stuff!
public class SpriteChangeExample : MonoBehaviour {
// we create a variable to store our sprite renderer for easy referencing and set to empty/null.
private SpriteRenderer thisSprite = null;
// we now create a variable for our polygon collider so our sprite has a neat new 2dcollider that fits comfortably!
private PolygonCollider2D poly = null;
// this is our url we reference and it should point to where the sprite is stored on the web!
private string url = "http://grimmstudios.net/KeyCatch/Player.png";
void Start(){
// lets get our sprite renderer to load the new sprite into!
thisSprite = this.GetComponent<SpriteRenderer>();
// load dynamic sprite using coroutine and www.
StartCoroutine(LoadTexture());
}
void Update(){
}
IEnumerator LoadTexture() {
// our www using our specified url variable.
WWW www = new WWW(url);
// lets wait for our www!
yield return www;
// after our www call for the new url sprite we now create a new sprite using the url sprite/texture and the vector2
// is the part where we set the center of the sprite.
Sprite sprite = Sprite.Create(www.texture,new Rect(0,0,www.texture.width,www.texture.height),new Vector2(0.5f,0.5f));
// set the new sprite to our sprite renderer!
thisSprite.sprite = sprite;
// add our polygon collider now to our new sprite/gameobject for much more snugg collision!
poly = this.gameObject.AddComponent<PolygonCollider2D>();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment