Search code examples
unity-game-enginengui

Unity3D - Create a NGUI Button


I'm working on some project where I need to create on the fly, buttons with NGUI. I found some answers but none of them could help me. Iknow it's simple but according to what I found on http://www.tasharen.com/forum/index.php?topic=81.0 and in NGUI script (UICreateWidgetWizard.cs), like:

            UILabel lbl = NGUITools.AddWidget<UILabel>(go);

it's still not working..

An my code is the following:

            UIButton button =  NGUITools.AddWidget<UIButton>(parent);

Thanks for yout help guys !


Solution

  • Either as @pfranza suggests, create a prefab of your UIButtons that you can reference as a public object in your script, then to create it use the

    GameObject newButton = NGUITools.AddChild(mParentGameObject, mButtonPrefab);
    

    Alternatively, you can fully create it at runtime if you wish:

        UISprite mButtonSprite = NGUITools.AddSprite(mParentGameObject, mAtlas, "Button");
        //Button is the name of the sprite in the atlas
    
        mButtonSprite.MakePixelPerfect();
        NGUITools.AddWidgetCollider(mButtonSprite.gameObject);
        mButtonSprite.gameObject.AddComponent<UIButton>();
        //add any further components/set up you like.