问题描述:

In case of a Unity mobile app, would it be good (at all) for performance, to deactivate the navigation through canvas objects like TextFields and Buttons?

When selecting e.g. a Button or TextField in the sceneview, the inspector shows the option "Navigation", which can be set to different things and can also be visualized. This feature is usually used to tab through input fields, like you would expect it on a website. On my mobile game I don't need this "tabbing". Would there be any sort of performance increase if I deactivated it everywhere?

网友答案:

Would deactivating this rather be a waste of time, or even make performance worse for some obscure reason?

Usually there are 3 ways to show and hide UI. I will list them from worst to best.

1.Instantiate (Show), Destroy (Hide).

public GameObject uiPanelPrefab;

void Start()
{
    //Show
    Instantiate(uiPanelPrefab);
    //Hide
    Destroy(uiPanelPrefab);
}

This creates and destroys Objects each time. (Not Recommended).

2.Activate (Show) or Deactivate (Hide) the GameObject of that UI.

public GameObject uiPanelPrefab;

void Start()
{
    //Show
    uiPanelPrefab.SetActive(true);
    //Hide
    uiPanelPrefab.SetActive(false);
}

This creates garbage each time it is set to active and also cause quick freezes. You will notice this a lot when making VR apps. Fine on Desktops. Not good or recommended on mobile devices.

3.Enable (Show) or Disable (Hide) the Component of that UI.

public GameObject uiPanelPrefab;

void Start()
{
    //Show
    uiPanelPrefab.GetComponent<Image>().enabled = true;
    //Hide
    uiPanelPrefab.GetComponent<Image>().enabled = false;
}

This simply enables and disables the components. This method requires a custom function for each UI Control such as Button, Text, InputField as each Control has different components attached to them. This is the recommended method especially on mobile devices.


After long experiment with these, I came to conclusion that #3 is the best and should be used.The downside is that you have to make a function that will disable every components of each UI Control.

For example, the Button Control has more than 1 components. Simply disabling the Button component will not do it. You have to write a simple function that will disable Button, Image and Text components. Something like below:

void showButton(GameObject button, bool show, bool includeInactive = false)
{
    Button bt = button.GetComponentInChildren<Button>(includeInactive);
    bt.enabled = show;

    Text txt = button.GetComponentInChildren<Text>(includeInactive);
    txt.enabled = show;

    Image img = button.GetComponentInChildren<Image>(includeInactive);
    img.enabled = show;
}

Usage:

//Show
showButton(uiPanelPrefab, true);

//Hide
showButton(uiPanelPrefab, false);
相关阅读:
Top