Unity Create UI control from script

blackMoon picture blackMoon · Dec 17, 2016 · Viewed 8.1k times · Source

I created a toggle by code but it won´t get displayed. Furthermore, I can´t change the position of my text field. I tried a lot and nothing works. This is my current version, maybe you see the mistake.

I´m new to Unity and it is very difficult.

public class Game : MonoBehaviour 
{

    public GameObject canvas;

    void Start () 
    {
        GameObject newGO = new GameObject("myTextGO");
        newGO.transform.SetParent(this.transform);
        newGO.transform.position = new Vector3(0, 0, 0);

        Text myText = newGO.AddComponent<Text>();
        myText.text = "Ta-dah!";
        Font ArialFont =  
           (Font)Resources.GetBuiltinResource(typeof(Font),"Arial.ttf");
        myText.font = ArialFont;
        myText.material = ArialFont.material;
        myText.color = Color.black;
        myText.transform.position = new Vector3(0, 10, 0);

        GameObject secGO = new GameObject("myGO");
        secGO.transform.SetParent(this.transform);
        Toggle myToggle = secGO.AddComponent<Toggle>();
        myToggle.isOn = true;
        myToggle.transform.position = new Vector3(10, 10, 0);
    }
}

Answer

Programmer picture Programmer · Dec 19, 2016

You are supposed to make the Toggle the child of the Canvas. You didn't do that in your code. Also, you move a UI component and GameObject with newGO.GetComponent<RectTransform>().anchoredPosition3D not newGO.transform.position.

There are 3 Ways to create a Complete UI Control in Unity:

1.Use the DefaultControls API to generate it (Easy and Recommended)

With the DefaultControls class, Unity will create the supplied UI then returns the parent of the UI. This is the easiest and recommended way of doing this. It takes DefaultControls.Resources as parameter so that you can provide the sprites to use when creating the default UI Control.

Button:

public GameObject canvas;
void Start()
{
    DefaultControls.Resources uiResources = new DefaultControls.Resources();
    //Set the Button Background Image someBgSprite;
    uiResources.standard = someBgSprite;
    GameObject uiButton = DefaultControls.CreateButton(uiResources);
    uiButton.transform.SetParent(canvas.transform, false);
}

Toggle:

public GameObject canvas;
void Start()
{
    DefaultControls.Resources uiResources = new DefaultControls.Resources();
    //Set the Toggle Background Image someBgSprite;
    uiResources.background = someBgSprite;
    //Set the Toggle Checkmark Image someCheckmarkSprite;
    uiResources.checkmark = someCheckmarkSprite;
    GameObject uiToggle = DefaultControls.CreateToggle(uiResources);
    uiToggle.transform.SetParent(canvas.transform, false);
}

Slider:

public GameObject canvas;
void Start()
{
    DefaultControls.Resources uiResources = new DefaultControls.Resources();
    //Set the Slider Background Image someBgSprite;
    uiResources.background = someBgSprite;
    //Set the Slider Fill Image someFillSprite;
    uiResources.standard = someFillSprite;
    //Set the Slider Knob Image someKnobSprite;
    uiResources.knob = someKnobSprite;
    GameObject uiSlider = DefaultControls.CreateSlider(uiResources);
    uiSlider.transform.SetParent(canvas.transform, false);
}

Panel:

public GameObject canvas;
void Start()
{
    DefaultControls.Resources uiResources = new DefaultControls.Resources();
    //Set the Panel Background Image someBgSprite;
    uiResources.background = someBgSprite;
    GameObject uiPanel = DefaultControls.CreatePanel(uiResources);
    uiPanel.transform.SetParent(canvas.transform, false);
}

InputField:

public GameObject canvas;
void Start()
{
    DefaultControls.Resources uiResources = new DefaultControls.Resources();
    //Set the InputField Background Image someBgSprite;
    uiResources.inputField = someBgSprite;
    GameObject uiInputField = DefaultControls.CreateInputField(uiResources);
    uiInputField.transform.SetParent(canvas.transform, false);
    uiInputField.transform.GetChild(0).GetComponent<Text>().font = (Font)Resources.GetBuiltinResource(typeof(Font), "Arial.ttf");
}

Dropdown:

public GameObject canvas;
void Start()
{
    DefaultControls.Resources uiResources = new DefaultControls.Resources();
    //Set the Dropdown Background and Handle Image someBgSprite;
    uiResources.standard = someBgSprite;
    //Set the Dropdown Scrollbar Background Image someScrollbarSprite;
    uiResources.background = someScrollbarSprite;
    //Set the Dropdown Image someDropDownSprite;
    uiResources.dropdown = someDropDownSprite;
    //Set the Dropdown Image someCheckmarkSprite;
    uiResources.checkmark = someCheckmarkSprite;
    //Set the Dropdown Viewport Mask Image someMaskSprite;
    uiResources.mask = someMaskSprite;
    GameObject uiDropdown = DefaultControls.CreateDropdown(uiResources);
    uiDropdown.transform.SetParent(canvas.transform, false);
}

The rest of the UI Controls:

public static GameObject CreateImage(Resources resources);
public static GameObject CreateRawImage(Resources resources);
public static GameObject CreateScrollbar(Resources resources);
public static GameObject CreateScrollView(Resources resources);
public static GameObject CreateText(Resources resources);

3.Via prefab and Instantiate

This method requires that you have the UI already created and saved as a prefab, You can then Instantiate the UI when need.

Create a Toggle Control from the Editor then save it as a prefab. Delete the original one. You can then Instantiate the Toggle Control prefab during run-time and position or scale it if necessary.

public GameObject canvas;
public GameObject togglePrefab;

void Start()
{
    GameObject uiToggle = Instantiate(togglePrefab) as GameObject;
    uiToggle.transform.SetParent(canvas.transform, false);
    //Move to another position?
    uiToggle.GetComponent<RectTransform>().anchoredPosition3D = new Vector3(...,...,...);
    //Re-scale?
    uiToggle.GetComponent<RectTransform>().localScale = new Vector3(...,...,...);
}

2.Piece by Piece (Hard)

You do this by first creating a UI from the Editor then study the Hierarchy and components attached to it in the Editor and reproduce it via code.

GameObject->UI->Toggle

For example, this is what Toggle looks like:

enter image description here

1.Create a Toggle GameObject then make it child of the Canvas.

2.Create a Background GameObject then make it child of the Toggle GameObject.

3.Create a Checkmark GameObject then make it child of the Background GameObject.

4.Create a Label GameObject then make it child of the Toggle GameObject.

5.Now attach components like Image, Text and Toggle to each GameObject like it appears in the Editor.

In Code:

public GameObject canvas;

void Start()
{
    makeToggle();
}

void makeToggle()
{
    GameObject toggleObj = createToggleObj(canvas);
    GameObject bgObj = createBackgroundObj(toggleObj);
    GameObject checkMarkObj = createCheckmarkObj(bgObj);
    GameObject labelObj = createLabelObj(toggleObj);
    attachAllComponents(toggleObj, bgObj, checkMarkObj, labelObj);
}

//1.Create a *Toggle* GameObject then make it child of the *Canvas*.
GameObject createToggleObj(GameObject cnvs)
{
    GameObject toggle = new GameObject("Toggle");
    toggle.transform.SetParent(cnvs.transform);
    toggle.layer = LayerMask.NameToLayer("UI");
    return toggle;
}

//2.Create a Background GameObject then make it child of the Toggle GameObject.
GameObject createBackgroundObj(GameObject toggle)
{
    GameObject bg = new GameObject("Background");
    bg.transform.SetParent(toggle.transform);
    bg.layer = LayerMask.NameToLayer("UI");
    return bg;
}

//3.Create a Checkmark GameObject then make it child of the Background GameObject.
GameObject createCheckmarkObj(GameObject bg)
{
    GameObject chmk = new GameObject("Checkmark");
    chmk.transform.SetParent(bg.transform);
    chmk.layer = LayerMask.NameToLayer("UI");
    return chmk;
}

//4.Create a Label GameObject then make it child of the Toggle GameObject.
GameObject createLabelObj(GameObject toggle)
{
    GameObject lbl = new GameObject("Label");
    lbl.transform.SetParent(toggle.transform);
    lbl.layer = LayerMask.NameToLayer("UI");
    return lbl;
}

//5.Now attach components like Image, Text and Toggle to each GameObject like it appears in the Editor.
void attachAllComponents(GameObject toggle, GameObject bg, GameObject chmk, GameObject lbl)
{
    //Attach Text to label
    Text txt = lbl.AddComponent<Text>();
    txt.text = "Toggle";
    Font arialFont =
    (Font)Resources.GetBuiltinResource(typeof(Font), "Arial.ttf");
    txt.font = arialFont;
    txt.lineSpacing = 1;
    txt.color = new Color(50 / 255, 50 / 255, 50 / 255, 255 / 255);
    RectTransform txtRect = txt.GetComponent<RectTransform>();
    txtRect.anchorMin = new Vector2(0, 0);
    txtRect.anchorMax = new Vector2(1, 1);
    //txtRect.y

    //Attach Image Component to the Checkmark
    Image chmkImage = chmk.AddComponent<Image>();
    chmkImage.sprite = (Sprite)AssetDatabase.GetBuiltinExtraResource(typeof(Sprite), "UI/Skin/Checkmark.psd");
    chmkImage.type = Image.Type.Simple;

    //Attach Image Component to the Background
    Image bgImage = bg.AddComponent<Image>();
    bgImage.sprite = (Sprite)AssetDatabase.GetBuiltinExtraResource(typeof(Sprite), "UI/Skin/UISprite.psd");
    bgImage.type = Image.Type.Sliced;
    RectTransform bgRect = txt.GetComponent<RectTransform>();
    bgRect.anchorMin = new Vector2(0, 1);
    bgRect.anchorMax = new Vector2(0, 1);

    //Attach Toggle Component to the Toggle
    Toggle toggleComponent = toggle.AddComponent<Toggle>();
    toggleComponent.transition = Selectable.Transition.ColorTint;
    toggleComponent.targetGraphic = bgImage;
    toggleComponent.isOn = true;
    toggleComponent.toggleTransition = Toggle.ToggleTransition.Fade;
    toggleComponent.graphic = chmkImage;
    toggle.GetComponent<RectTransform>().anchoredPosition3D = new Vector3(0, 0, 0);
}

Method #3 is the hardest way to do this so, you should avoid it. Method #1 Should be fine in this case.