How to change an UI Image and it sizes by code?

Very simple problem, I have 3 UI images that are white squares in the inspector, at the start of the game I have a script in the gameManager object that takes an array containing 5 prefab images and randomly put 3 of their sprites as the 3 blank UI images. Its work actually, every time I start the game there’s 3 images, but the problem is with the size, it seems that Unity just fit the images in the space the square occupies, so the image appears deformed.

**How its in the scene
9656984--1374428--upload_2024-2-21_17-51-51.png

**How the image appears (I want them to appear like the gameobject at the right)

The code used:

    private void CreateObjective()
    {
        for(int i = 0; i < 3; i++)
        {
            //random number
            int randomIndex = UnityEngine.Random.Range(0, candiesPrefabs.Length);

            //Set what candy needs to be destroyed to win the game(ignore this)
            candiesObjective[i] = candiesPrefabs[randomIndex];

            //Set the image of the candie to the blank square (CandiesdPrefabs are the game object prefabs, candiesSprites are Ui Image, both arrays have the same order)
            imgSlider[i].sprite = candiesSprites[randomIndex].sprite;
            //Debug.Log(candiesObjective[i]);   
        }
    }

on the image component there is a “preserve aspect” option that will preserve the aspect ratio of which ever sprite is added.

It should fix the aspect ratio but it may break the overall size of the image and cause the images to overlap if you do not have the anchors properly set. look at the basic layout docs for RectTransform, you’ll likely want to use one of the stretch options on the anchor presets, depending on how you have its parent layout setup.

1 Like

its perfect thank you so much