Home > Blockchain >  How to get an image from a url and set it to an object in Unity
How to get an image from a url and set it to an object in Unity

Time:03-12

I have a method to create objects from prefabs. The prefab consists of the texts "Title" and "Description", as well as the image "Image".
enter image description here

In the method below, I get the text for "Title", "Description" and the URL of the image for "Image".

void InitializeItemView (GameObject viewGameObject, string TextTitle, string TextDescription, string URLImg)
    {
        TestItemView view = new TestItemView(viewGameObject.transform);
        view.Title.text = TextTitle;
        view.Description.text = TextDescription;
        // view.Img.text = URLImg;
    }

    public class TestItemView
    {
        public Text Title;
        public Text Description;
        // public Text Img;

        public TestItemView (Transform rootView)
        {
            Title = rootView.Find("Title").GetComponent<Text>();
            Description = rootView.Find("Description").GetComponent<Text>();
            // Image = rootView.Find("Image").GetComponent<Image>();
        }
    }

I don't understand how can I get an image from an image url and set its value to "Image". enter image description here

But I am a beginner, so it is desirable that you explain something in simple terms.

CodePudding user response:

Image doesn't have an attribute of Text, and instead you should get the file, load the image to a texture and set the Image's sprite as the texture.

File fileData;
Texture2d txture;
 (File.Exists(URLImg))     {
         fileData = File.ReadAllBytes(URLImg); //read the bytes from the file at URLImg's destination
         txture = new Texture2D(0,0);//makes the new texture
         txture.LoadImage(fileData);//loads the image from the file
         view.Img.sprite = Sprite.Create(txture, new Rect(0,0,200,200), new Vector2());
         //set Img.sprite to a new sprite at 0,0 with the dimensions 200x200
     }

with view.Img.sprite as an image rather than "text" because it's not painting text and rather an image.

CodePudding user response:

Unity Beginner has explained it easily in just 1.5 minutes to Load Image from WebLink or URL.

But here, they used WWW, which is obsolete, so use UnityWebRequest instead. Here are the changes you need to perform while changing from WWW to UnityWebRequest.

  • Related