Search code examples
c#arraysunity-game-enginetexturesunity3d-gui

Generate GameObjects and set their image from an Array of Textures when a button is clicked - Unity 4.6 (using uGUI)


I'm having a lot of trouble trying to develop a loader that when a button gets clicked it takes an array of textures and populates them into a grid layout (and when another button is clicked it removes the current textures and replaces them with a new array of textures). I have the grid layout portion of the UI fully sorted and the Texture arrays are generated, I just need help with:

  1. Assigning each texture to an Image component of individually generated GameObjects.
  2. Populating the grid layout it with those GameObjects.

Could anyone share some code insight or a snippet that might do the trick?


Solution

  • First create script inside of your Canvas or create empty GameObject with script.

    Create public variables:

    public Sprite[] mySprites;
    public GameObject myGridLayoutGameObject;
    public GameObject myGridElement;
    

    In mySprites assign all your sprites via editor.

    For myGridLayoutGameObject assign your GUI GameObject with GridLayoutGroup.

    For myGridElement, you must create prototype GUI object with Image and place it outside of your canvas, in order to make it not visible for your camera. Assign it to your scripts variable.

    Then you can create some method:

    public void fillGrid() {
        foreach (Sprite sprite in mySprites) {
            GameObject instance = Instantiate(myGridElement, myGridElement.transform.position, myGridElement.transform.rotation) as GameObject;
            instance.GetComponent<Image>().sprite = sprite;
            instance.transform.SetParent(myGridLayoutGameObject.transform);
        }
    }
    

    It will automatically place all your objects inside grid, depending on your settings. Do not forget to add using UnityEngine.UI; on head of your script.

    Also, I have written this code for Unity 5. Unity 4.6 may have some differencies on GUI elements.