Unity从脚本创建UI控件 [英] Unity Create UI control from script

查看:265
本文介绍了Unity从脚本创建UI控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过代码创建了一个切换开关,但不会显示. 此外,我无法更改文本字段的位置. 我尝试了很多,但没有任何效果.这是我当前的版本,也许您看到了错误.

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.

我是Unity新手,很难.

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);
    }
}

推荐答案

您应该将Toggle设为Canvas的子级.您没有在代码中这样做.另外,您可以使用newGO.GetComponent<RectTransform>().anchoredPosition3D而不是newGO.transform.position来移动UI组件和GameObject.

You are supposed to make the 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.

有3种方法可以在Unity中创建完整的UI控件:

1.使用 DefaultControls API生成它(简单且推荐)

使用DefaultControls类,Unity将创建提供的UI,然后返回UI的父级.这是最简单且推荐的方法. 它使用 DefaultControls.Resources 作为参数,以便您可以将精灵提供给在创建默认的UI控件时使用.

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.

按钮:

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);
}

切换:

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);
}

滑块:

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);
}

面板:

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");
}

下拉列表:

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);
}

其余的UI控件:

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.通过预制并实例化

此方法要求您已经创建了UI并将其保存为预制件,然后可以在需要时Instantiate UI.

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

从编辑器中创建一个Toggle控件,然后将其另存为预制件.删除原始的.然后,您可以在运行时Instantiate Toggle控制预制件,并在必要时定位或缩放比例.

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.一件一件(硬件)

您首先要通过编辑器创建一个UI,然后研究层次结构及其在编辑器中附加的组件,然后通过代码进行复制.

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:

1 .创建一个 Toggle 游戏对象,然后使其成为 Canvas 的子代.

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

2 .创建一个 Background 游戏对象,然后使其成为 Toggle GameObject的子对象.

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

3 .创建一个 Checkmark 游戏对象,然后使其成为 Background GameObject的子对象.

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

4 .创建一个 Label 游戏对象,然后使其成为 Toggle GameObject的子代.

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

5 .现在,像在编辑器中一样,将ImageTextToggle之类的组件附加到每个GameObject.

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

在代码中:

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);
}

方法#3 是执行此操作的最困难的方法,因此应避免使用它.方法#1 在这种情况下应该没问题.

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

这篇关于Unity从脚本创建UI控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆