- Home /
Cast object as sprite for UI Image
Hello!
I have a list of objects (Texture2D and Texture) and I want to use the Texture 2D objects as sprites on a GUI image.
How can I cast the objects from the list that are Texture2D as sprite?
So far I've got this but the sprite field in the image stays empty... :
 foreach (Object obj in objectList) {
 
     System.Type type = obj.GetType();
 
     if (type == typeof(UnityEngine.Texture2D)) {
 
         Image newImage = (GalleryImage)Instantiate(imagePrefab);
 
         newImage.sprite = obj as Sprite;
 
     }
 
 }
Can you help please?
               Comment
              
 
               
               
               Best Answer 
              
 
              Answer by monogon · Feb 26, 2015 at 11:44 PM
Nevermind, got it more or less:
 foreach (Object obj in objectList) {
 
     System.Type type = obj.GetType();
 
     if (type == typeof(UnityEngine.Texture2D)) {
 
         Image newImage = (GalleryImage)Instantiate(imagePrefab);
 
         Texture2D tex = obj as Texture2D;
 
         Sprite newSprite = Sprite.Create(obj as Texture2D, new Rect(0f, 0f, tex.width, tex.height), Vector2.zero);
 
         newImage.sprite = newSprite;
         newImage.transform.SetParent(this.transform);
 
     }
 
 }
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                