In my project, I’m trying to load PNG images from the Resources folder and instantiate them as UI Image components on a canvas. It seems to mostly be working, however, it’s seemingly coming up with numerous extra images that do not exist. They consist of cubes that are either 1x1 or 5x5 pixels. It instantiates 19 items based on a folder of 6 images. Would I be able to get some advice and guidance? Here is the code I’m using and a screenshot demonstrating the extra images:
using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic;
public class PopulateGallery : MonoBehaviour
{
public Transform gridParent; // UI Grid parent
public string resourcePath; // Folder containing PNGs
public GameObject imagePrefab; // Prefab for displaying sprites
public void Awake()
{
Texture2D[] textures = Resources.LoadAll<Texture2D>(resourcePath);
foreach (Texture2D texture in textures)
{
// Convert Texture2D to Sprite
Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.one * 0.5f);
// Create UI Image object and add it to the grid
GameObject imageObject = Instantiate(imagePrefab, gridParent);
Image image = imageObject.GetComponent<Image>();
image.sprite = sprite;
}
}
}