Author Topic: Creating UISprites via code problem  (Read 5317 times)

RexSpaceman

  • Guest
Creating UISprites via code problem
« on: November 19, 2012, 01:00:50 PM »
So I am just getting started with NGUI. I made a little test class:

  1. public class TestUI : MonoBehaviour
  2. {
  3.     UISprite[] sprites;
  4.     GameObject[] GOs;
  5.     public GameObject panel;
  6.  
  7.     public UIAtlas uiatlas;
  8.  
  9.     void Start()
  10.     {
  11.         sprites = new UISprite[1];
  12.         GOs = new GameObject[1];
  13.  
  14.         GOs[0] = new GameObject("testLabel");
  15.         sprites[0] = GOs[0].AddComponent<UISprite>();
  16.  
  17.         GOs[0].transform.parent = panel.transform;
  18.  
  19.         sprites[0].atlas = uiatlas;
  20.         sprites[0].sprite = sprites[0].atlas.GetSprite("TestIcon");
  21.  
  22.     }
  23. }

TestUI is currently placed on a new gameobject in the scene. panel is the NGUI panel in the scene. uiatlas references the UI Atlas prefab.

There are several defined sprites in the atlas. TestIcon was the 3rd or 4th defined.

When I set the transform.parent for the GO, the sprite becomes sprite index 0, aka NOT "TestIcon".

If I set the parent AFTER the sprite assignment I get the same outcome. If I don't set the GO's parent at all, the sprite assignment does work.

So, what am I doing wrong? How can I programmatically create UI sprites?

RexSpaceman

  • Guest
Re: Creating UISprites via code problem
« Reply #1 on: November 19, 2012, 01:23:25 PM »
I've also tested via the editor. If I create the GO and UISprite unparented, and then drag it into the hierarchy, it resets the sprite.

I've also tried setting the parent first, and adding the UISprite component after the parenting. Same result.

:(

RexSpaceman

  • Guest
Re: Creating UISprites via code problem
« Reply #2 on: November 19, 2012, 01:56:28 PM »
So I did more digging into the code, and I think I figured it out. Posting this as an update.

Apparently I was over doing it.

So all I had to do was:

  1. sprites[0].atlas = uiatlas;
  2. sprites[0].spriteName = "TestIcon";

So simple! Thanks.