Load Images from C# code and show in UI

I want to write code that loads images from different Resources sub folders and display them in the UI.
I’ve tried many different solutions from the forums already, but nothing seems to work for me.
For testing I just want to load a single image and display it.

First I have created an image object (MyImage) on the canvas I want it to be displayed.
Then I added my script as a component to the image.
I created a public Image variable in my script and tried loading an image from a folder to it.

public Image img1;

    // Start is called before the first frame update
    void Start()
    {
        img1 = Resources.Load<Image>("ARInfo/Magazine1/1");
    }

Then I dragged my image to the public variable field in the Inspector.

4170127--368323--Capture.PNG

When I run my code, the image won’t load though and it keeps showing just a white box.
Can anyone tell me what I need to do instead?
Complete Beginner here…

The code you are using are used to load the image into the variable field in the inspector itself, you shouldt need to put it in manual upon running the game.

replace the image code in ur start method with:

img1 = GetComponent();

The image is attached to the same game object as the script is meaning you dont have to search for it in the project and thus can just set the img1 to the Image componenet of your object, thus making the Image - Source Image field apply the same picture as your Test script img1

Thanks for your reply!
I just tried this and am still getting the same results. The image is just a white square…

If I just use img1 = GetComponent(); how is the script supposed to know which picture to load, there are many in my Resources sub folders and using only this code I never specify what picture I want or where it’s located?

I have now managed to find a solution. The problem was that I didn’t have my Image Object referenced in the code. This code is working now:

public class Test : MonoBehaviour
{
    private Sprite img1;
    public GameObject MyImage;

    // Start is called before the first frame update
    void Start()
    {
        MyImage.AddComponent(typeof(Image));
        img1 = Resources.Load<Sprite>("ARInfo/Magazine1/1");
        MyImage.GetComponent<Image>().sprite = img1;
        Debug.Log("Test script started");
    }
}
2 Likes

@Aster321 For me your code worked with an additional

GameObject MyImage = new GameObject();

at the start of Start()

Thank you for sharing

For some reason, using this method of creating an image resizes my image to a square. Does anyone know why that might be?

I mean look, is the GameObject that ure assigning a sprite to a box? An image is, by default a box.