- Home /
Cast Texture2d to Sprite
string url = "http://1drv.ms/1bCdLy1";
www = new WWW(url);
StartCoroutine(WaitForWWW());
portraitSprite.sprite = (Sprite)www.texture;
private IEnumerator WaitForWWW() {
yield return www;
}
versus
Cannot convert type 'UnityEngine.Texture2D' to 'UnityEngine.Sprite
Any ideas? new to Unity..
Answer by Cenda · May 30, 2015 at 11:34 AM
I just solved exactly same problem with Sprite.Create. It is working in editor, but not on device. It looks that device can not use Sprite.Create, so I have to use texture and RawImage.
Answer by muratrishit · Jun 07, 2016 at 09:05 AM
IEnumerator Start()
{
WWW www = new WWW(url);
yield return (www);
gameObject.GetComponent<Image>().overrideSprite = Sprite.Create(www.texture, new Rect(0, 0, 900, 360), new Vector2(0.5f, 0.5f));
}
Answer by Atulyextel2 · Jun 06, 2018 at 01:28 PM
Hi, this can help
// reading texture from images in system local
Blockquote
public static Texture2D LoadPNG(string filePath) { Texture2D tex = null; byte[] fileData;
if (File.Exists(filePath))
{
fileData = File.ReadAllBytes(filePath);
tex = new Texture2D(2, 2);
tex.LoadImage(fileData); //..this will auto-resize the texture dimensions.
}
return tex;
}
Blockquote
then save the texture from LoadPNG function
Blockquote
mytexture = LoadPNG(thumbnailpath); obj.GetComponentInChildren().sprite = Sprite.Create(mytexture, new Rect(0.0f, 0.0f, mytexture.width, mytexture.height), new Vector2(0.5f, 0.5f), 100.0f);
Blockquote