How to set prefab images from script?

I have an inventory panel with a grid layout. I instantiate slots in it. Slot is just an image. I made a prefab called Slot. I am adding the slots to the grid via script. How can I set the image in a script like below?

for (int i=0; i< database.items.Count; i++) {
  Texture2D icon = database.items*.icon);*

GameObject newSlot = Instantiate(slot) as GameObject;
newSlot.transform.SetParent(GameObject.FindObjectOfType().gameObject.transform, false);
//newSlot.getComponent<image??> = icon

I found my problem.

First import UnityEngine.UI so you can do


Then load the sprite from root folder. My images were in a folder called Resources. I was trying to load it as

Resources.Load("Resources/" + filename);

while the path should have been just:


It is strange but finally it worked.

Hi, I have the same issue, could you detail your solution?