8
\$\begingroup\$

So I've been fiddling around with the new UI system recently -- and one problem I have is adding images of my sprites to the ui.

I know I can create a prefab of an image gameobject with the sprite I want, but I have hundreds of the sprites I want to add to the ui (They're different characters) so I don't want to create hundreds of prefabs. Instead, what I want to do is in a script, create an image gameobject, set its sprite, and child it to a parent panel in my canvas. Is this possible?

\$\endgroup\$
11
\$\begingroup\$

Its entirely possible. Here's a simple script showing how.

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;

public class PopulateSprites : MonoBehaviour {

public List<Sprite> Sprites = new List<Sprite>(); //List of Sprites added from the Editor to be created as GameObjects at runtime
public GameObject ParentPanel; //Parent Panel you want the new Images to be children of

// Use this for initialization
void Start () {
    foreach (Sprite currentSprite in Sprites)
    {
        GameObject NewObj = new GameObject(); //Create the GameObject
        Image NewImage = NewObj.AddComponent<Image>(); //Add the Image Component script
        NewImage.sprite = currentSprite; //Set the Sprite of the Image Component on the new GameObject
        NewObj.GetComponent<RectTransform>().SetParent(ParentPanel.transform); //Assign the newly created Image GameObject as a Child of the Parent Panel.
        NewObj.SetActive(true); //Activate the GameObject
    }
}

}

Unity Reference for AddComponent: AddComponent

\$\endgroup\$
1
  • \$\begingroup\$ Some additional comments in this code would make it up-vote worthy. \$\endgroup\$
    – House
    Jun 15 '15 at 14:30

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .