Search Unity

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

Discussion in 'Scripting' started by murilohue779, Feb 21, 2024.

  1. murilohue779

    murilohue779

    Joined:
    May 15, 2023
    Posts:
    3
    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
    upload_2024-2-21_17-51-51.png

    **How the image appears (I want them to appear like the gameobject at the right)
    upload_2024-2-21_17-44-5.png

    The code used:
    Code (CSharp):
    1.     private void CreateObjective()
    2.     {
    3.         for(int i = 0; i < 3; i++)
    4.         {
    5.             //random number
    6.             int randomIndex = UnityEngine.Random.Range(0, candiesPrefabs.Length);
    7.  
    8.             //Set what candy needs to be destroyed to win the game(ignore this)
    9.             candiesObjective[i] = candiesPrefabs[randomIndex];
    10.  
    11.             //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)
    12.             imgSlider[i].sprite = candiesSprites[randomIndex].sprite;
    13.             //Debug.Log(candiesObjective[i]);  
    14.         }
    15.     }
     
  2. JoshuaMcKenzie

    JoshuaMcKenzie

    Joined:
    Jun 20, 2015
    Posts:
    916
    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.
     
    murilohue779 likes this.
  3. murilohue779

    murilohue779

    Joined:
    May 15, 2023
    Posts:
    3
    its perfect thank you so much