Unity UI optimization tips, understanding of official documents translation (four)

5.Optimizing UI Controls - optimized UI controls


UI text


Unity’s built-in Text component is a convenient way of displaying rasterized text glyphs within a UI. However, there are a number of behaviors that are not commonly known, yet frequently appear as performance hotspots. When adding text to a UI, always remember that the text glyphs are actually rendered as individual quads, one per character. These quads tend to have a significant amount of empty space surrounding the glyph, depending on its shape, and it is very easy to position text in such a way that it unintentionally breaks the batching of other UI elements.


Unity is a built-Text component a convenient way text font rasterization in the UI. However, there are many cases inadvertently lead to serious performance overhead. When you add text to the UI, please always remember as a text symbol is actually a quad to show each character a. The shape of the glyph, which tend to have large quad blank around the shape, it is easy to accidentally destroyed the batch engagement of other UI elements.


Text mesh rebuilds


One major issue is the rebuilding of UI text meshes. Whenever a UI Text component is changed, the text component must recalculate the polygons used to display the actual text. This recalculation also occurs if a text component, or any of its parent GameObjects, is simply disabled and re-enabled without changes to the text.

This behavior is problematic for any UI that displays large numbers of textual labels, with the most common being leaderboards or statistics screens. As the most common way to hide and show a Unity UI is to enable/disable a GameObject containing the UI, UIs with large numbers of text components will often cause undesirable frame-rate hiccups whenever they are displayed.

For a potential workaround to this issue, see the Disabling Canvases section in the next step.


One major problem is that UI text grid redraw (rebuild). Whenever you change the UI Text component, the component must recalculate the polygons used to display the actual text. If you simply disable or re-enable the Text component (or any of its parent game objects), but not make changes to text, which can also occur recalculated.

This behavior UI for displaying large amounts of text there is a problem, the most common is the ranking data or billing interface. Due to hide and show the most common way to Unity UI is enabled / disabled GameObject containing the UI, it has a large amount of text in the display UI components often results in unexpected frame rate drop.

Want to solve this problem, please see the next part of Disabling Canvases


Dynamic fonts and font atlases - dynamic font and font Atlas


Dynamic fonts are a convenient way to display text when the full displayable character set is either very large, or not known prior to runtime. In Unity’s implementation, these fonts build a glyph atlas at runtime based on the characters encountered within UI Text components.

Each distinct Font object loaded will maintain its own texture atlas, even if it is in the same font family as another font. For example, using Arial with bolded text on one control while using Arial Bold on another control will produce identical output but Unity will maintain two distinct texture atlases - one for Arial and one for Arial Bold.

When the character to be displayed is very large, or do not know what word to be displayed before you run, you need a dynamic font. Unity in the implementation of these fonts at run time to build a portfolio based on the character glyphs UIText assembly required.

Each different fonts are stored in their own atlas in, even if it's just the same font family in another font. For example, using bold Arial font on a control, use Arial Bold font on another control, the ultimate They look the same, but the Unity but needs to maintain two different fonts Atlas - one for Arial, one for Arial Bold.


From a performance perspective, the most important thing to understand is that Unity UI’s dynamic fonts maintain one glyph in the font’s texture atlas for each distinct combination of size, style & character. That is, if a UI contains two text components, both displaying the letter ‘A’, then:

  • If the two Text components share the same size, the font atlas will have one glyph in it.
  • If the two Text components do not share the same size (e.g. one is 16-point, the other 24-point), then the font atlas will contain two copies of the letter ‘A’ at different sizes.
  • If one Text component is bold and the other is not, then the font atlas will contain a bold 'A' and a regular 'A'.


Whenever a UI Text object with a dynamic font encounters a glyph that has not yet been rasterized into the font’s texture atlas, the font’s texture atlas must be rebuilt. If the new glyph fits into the current atlas, it is added and the atlas re-uploaded to the graphics device. However, if the current atlas is too small, then the system attempts to rebuild the atlas. It does this in two stages.

From a performance standpoint, the most important thing is to understand the Unity UI dynamic font in the font atlases each different combination of size, style and character to maintain a glyph. That is, if a UI text contains two components, both the letter "A", then:

  • Text If the two components have the same size, the font will generate a glyph FIG concentrated.
  • If the two are not the same size Text component (e.g., a number is 16, and the other is 24), then the portfolio comprises two different font sizes letter "A".
  • If the component is a Text in bold, the other is not, then the portfolio comprising a bold font 'A' and a common 'A'.

When using the dynamic font UI Text input has not added to the font glyph to Atlas, Atlas fonts must be redrawn. If the new glyph can be placed directly into the current Atlas, Atlas then add it and re-upload to the graphics device. However, if the current Atlas is too small, the system will attempt to re-create the atlas. It is divided into two stages.


First, the atlas is rebuilt at the same size, using only the glyphs currently being shown by active UI Text components. This includes UI Text components whose parent Canvases are enabled, but that have disabled Canvas Renderers. If the system succeeds in fitting all currently-in-use glyphs into a new atlas, it rasterizes that atlas and does not continue to the second step.

Second, if the set of currently-in-use glyphs cannot be fit into an atlas of the same size as the current atlas, a larger atlas is created by doubling the atlas’ shorter dimension. For example, a 512x512 atlas expands into 512x1024 atlas.

First, create an atlas of the same size, all open on the current state of UIText interface components, including those opened but the parent Canvas disabled glyphs on Canvas Renderers of UIText component attempts to join the Atlas. If the system successfully placed all the glyphs are currently using a new atlases, it will rasterize the atlas, and will not proceed with the second step.

Second, if all glyphs currently in use can not be put into the same size of the current atlas atlases, the Atlas by the shorter dimension is doubled to create a large atlas. For example, 512x512 to 512x1024 Atlas Atlas extension.


Due to the above algorithm, a dynamic font’s atlas will only grow in size once created. Given the cost of rebuilding the texture atlases, it is imperative to minimize during rebuilds. This can be done in two ways.

Whenever possible, use non-dynamic fonts and preconfigure support for the desired glyph set. This generally works well for UIs using a well-constrained character set, such as only the Latin/ASCII characters, and with a small range of sizes.

Due to the above algorithm, dynamic font atlas will only grow. When taking into account the performance overhead of rebuilding Atlas, the best minimally reduce the frequency of reconstruction. There are two solutions, the first: If possible, try to use non-dynamic font, which is the need of a glyph ahead Atlas. This usually applies to text specification of good UI (that is, have known what the word), for example, only use Latin / ASCII characters and smaller size range.


If an extremely large range of characters must be supported, such as the entire Unicode set, then the font must be set to Dynamic. To avoid predictable performance problems, prime the font’s glyph atlas at startup time with a set of appropriate characters via Font.RequestCharactersInTexture.

Note that font atlas rebuilds are triggered individually for each UI Text component that is changed. When populating an extremely large number of Text components, it may be advantageous to collect all unique characters in the Text components’ content and prime the font atlas. This will ensure that the glyph atlas need only be rebuilt once instead of being rebuilt once each time a new glyph is encountered.

If you need a very wide range of characters, such as the needs of the entire Unicode character set, it would have to use dynamic font. To avoid performance problems when the game starts by calling Font.RequestCharactersInTexture to initialize these text methods.

Please note that reconstruction is a font atlas for each UI Text component is changed separately triggered. When writing a lot of UI Text components, it is best to collect Text component content of all unique (not repeated) character to update the atlas in advance. This will ensure that the font atlas only need to rebuild once, not every time they meet a new font to be rebuilt again.


Also note that, when a font atlas rebuild is triggered, any characters that are not presently contained in an active UI Text component will not be present in the new atlas, even if they were originally added to the atlas as a result of a call to Font.RequestCharactersInTexture. To work around this limitation, subscribe to the Font.textureRebuilt delegate and query Font.characterInfo to ensure that all desired characters remain primed.

The Font.textureRebuilt delegate is currently undocumented. It is a single-argument Unity Event. The argument is the font whose texture was rebuilt. Subscribers to this event should follow the following signature

Note also that when a font atlas trigger reconstruction, in addition to the text is now displayed on all active (activeSelf = true) UI components, the other will not be added into the new atlas, even if they initially by Font. RequestCharactersInTexture method to the set of FIG. To work around this limitation, implement Font.textureRebuilt commissioned by Font.characterInfo to ensure that all the characters needed to maintain the status display method.

Here that Font.RequestCharactersInTextur E method is not a document, in fact, there have now API manual, check usage is like.


Specialized glyph renderers - special font renderer

For situations where the glyphs are well-known, with relatively fixed positions between each glyph, it is significantly more advantageous to write a custom component to display sprites displaying those glyphs. An example of this might be a score display.

For scores, the displayable characters are drawn from a well-known glyph set (the digits 0-9), do not change across localities, and appear at fixed distances from one another. It is relatively trivial to decompose an integer into its digits and display appropriate digit sprites. This sort of specialized digit-display system can be built in a manner that is both allocationless and considerably faster to calculate, animate and display than the Canvas-driven UI Text component.

The meaning here means that the number of commonly used (known) shape, and the distance between the word and the word is fixed, then the use of a custom display more useful than the Sprite to use UI Text assembly driven by the Canvas. For example, the display score (0-9), with no change in position, the distance between them is fixed.


Fallback fonts and memory usage - font fallback (Fallback) and memory usage

For applications that must support a large character-set, it is tempting to list a large number of fonts in the “Font Names” field of a font importer. Any fonts listed in the “Font Names” field will be used as fallbacks if a glyph cannot be located within the primary font. The fallback order is determined by the order in which the fonts are listed in the “Font Names” field.

However, in order to support this behavior, Unity will keep all fonts listed in the “Font Names” field loaded into memory. If a font’s character set is very large, then the amount of memory consumed by fallback fonts can become excessive. This is most often seen when including pictographic fonts, such as Japanese Kanji or Chinese characters.

If a lot of text (font) APP needs, easy to list a large number of fonts in the "Font Names" field importer font (font importer) in. If you can not find a font in the font it is being used in, then it will be all the fonts listed in the "Font Names" have to find a field in this shape. In order to find the font of the order by the "Font Names" field is listed in the decision.

All fonts To support this operation, Unity will be listed in the "Font Names" field are saved to memory. If the font character set is very large, then search the font memory consumed may be too much. Especially as Japanese and Chinese this pictograph.


Best Fit and performance - it's the best fit and performance

In general, the UI Text component's Best Fit setting should never be used.

Generally, you should not use the Best Fit setting UI Text component.

“Best Fit” dynamically adjusts the size of a font to the largest integer point size which can be displayed within a Text component’s bounding box without overflow, clamped to a configurable minimum/maximum point size. However, because Unity renders a distinct glyph into the font atlas for each distinct size of character being displayed, use of Best Fit will rapidly overwhelm the atlas with many different glyph sizes.

"Best Fit" dynamically adjust the font size is the maximum integer in the frame may be displayed without spilling, and cut within the minimum / maximum range of configurable. However, because Unity will be different for each character size of the display of focus to draw different glyphs in the font chart, so the use of "Best Fit" can cause font atlas was soon inundated with different font sizes.


As of Unity 2017.3, the size detection used by Best Fit is nonoptimal. It generates glyphs in the font atlas for each size increment tested, which further increases the amount of time required to generate font atlases. It also tends to cause atlas overflows, which causes old glyphs to be kicked out of the atlas. Due to the large number of tests required for a Best Fit calculation, this will often evict glyphs in use by other Text components, and force the font atlas to be rebuilt at least once more after the appropriate font size has been calculated. This specific issue has been corrected in Unity 5.4, and Best Fit will not unnecessarily expand the font's texture atlas, but is still considerably slower than statically-sized text.

In Unity 2017.3, the size detection using the Best Fit is not optimal. It is detected font size of each increment is applied to FIG concentrated, which further increases the time required to generate the font's portfolio. It can also lead to Atlas overflow, leading to the old glyph is concentrated kicked out from the figure. Since the Best Fit calculation requires a lot of testing, which usually exclude other Text-shaped components used, and forced to rebuild the font's portfolio after at least once calculated the appropriate font size. This problem has been corrected in the Unity 5.4, Best Fit will not unnecessarily expand the font atlas, but still much slower than the static size of the text.



Frequent font atlas rebuilds will rapidly degrade runtime performance as well as cause memory fragmentation. The greater the quantity of text components set to Best Fit, the worse this problem becomes.

Rebuild frequently font Atlas will quickly reduce run-time performance, and lead to memory fragmentation. The more the text is set to Best Fit number of components, this problem becomes more serious


TextMeshPro Text

TextMesh Pro (TMP) is a replacement for Unity’s existing text components like Text Mesh and UI Text. TextMesh Pro uses Signed Distance Field (SDF) as its primary text rendering pipeline making it possible to render text cleanly at any point size and resolution. Using a set of custom shaders designed to leverage the power of SDF text rendering, TextMesh Pro makes it possible to dynamically change the visual appearance of the text by simply changing material properties to add visual styles such as dilation, outline, soft shadow, beveling, textures, glow, etc. and to save and recall these visual styles by creating/using material presets.

Until the release of 2018.1, TextMesh Pro was included in one’s project as a Asset Store package. As of 2018.1 TextMesh Pro will be available as a Package Manager package.

Text Mesh Pro (TMP) replace the existing text Unity components. TextMesh Pro using Signed Disatance Fild (SDF) as the preferred text rendering pipeline so that it can clear at any size and resolution of the rendered text. Ability to use custom shader to enhance the SDF text rendering, TextMesh Pro may dynamically change the visual effects by simply changing the material.


Text mesh rebuilds

Much like Unity’s built-in UIText component, making changes to the text displayed by the component will trigger calls to Canvas.SendWillRendererCanvases and Canvas.BuildBatch which can be costly. Minimize changes to the text field of a TextMeshProUGUI component and make sure to parent TextMeshProUGUI components whose text changes often to a parent GameObject that has its own Canvas component to ensure that Canvas rebuild calls remain as efficient as possible.

Do note that for text displayed in world space, we recommend that users use the normal TextMeshPro component instead of using TextMeshProUGUI as using Canvases in Worldspace can be inefficient. Using TextMeshPro directly will be more efficient given it doesn't have incur the canvas system overhead.

Unity built UIText components change when the text will trigger Canvas.SendWillRendererCanvas methods and Canvas.BuildBatch method, very wasteful performance. The text in the component TextMeshProUGUI fluctuation is minimized and its assembly will be placed on changes to specific Canvas, Canvas redrawn so that the highest efficiency.

In the text to be displayed when the world space, it is recommended to use direct TextMeshPro, we will be more efficient, because he will not have the overhead canvas system.



Scroll Views

After fill-rate problems, Unity UI’s Scroll Views are the second most common source of runtime performance issues seen. Scroll Views generally require a significant number of UI elements to represent their content. There are two basic approaches to populating a scroll view:

  • Fill it with all of the elements necessary to represent all of the scroll view’s content
  • Pool the elements, repositioning them as needed to represent visible content.

Unity UI The Scroll View is the reason followed by fill-rate issues the second most common performance problems. Scroll Views requires a lot of UI elements indicate their content. There are two basic ways to fill scroll view:

  • The one-time view of all the rolling elements needed to load
  • Cache element, to reposition them when necessary elements

Both solutions will have some problems.


The first solution requires an increasing amount of time to instantiate all of the UI elements as the number of items to be represented increases, and also increases the time required to rebuild the Scroll View. If there are only a small number of elements required within a Scroll View, such as in a Scroll View that only needs to display a handful of Text components, then this method is favored for its simplicity.

The second solution requires significant amounts of code to implement correctly under the current UI and layout system. Two possible methods will be discussed in further detail below. For any significantly complex scrolling UI, some sort of pooling approach is generally needed to avoid performance problems.

Despite these issues, all approaches can be improved by adding a RectMask2D component to the Scroll View. This component ensures that Scroll View elements that are outside of the Scroll View’s viewport are not included in the list of drawable elements that must have their geometry generated, sorted and analyzed when rebuilding a Canvas.

The first solution requires more time to generate all UI elements, and with the increase of elements to be displayed, the time required for the rebuilt Scroll View will follow the increase. Scroll View if only a small amount of elements such as Text Scroll View only shows some components, then the solution is simple to use, the most appropriate.

The second solution requires a lot of code to achieve the correct UI and layout of the current system to be displayed. We will be further discussed two possible solutions in detail below. For those a large number of complex to scroll UI is usually required to use certain objects pool to avoid performance problems.

Despite these problems, all of the methods can be improved by adding to the assembly RectMask2D Scroll View. This ensures Scroll View component elements other than the viewport is not included in the list of elements to be drawn, the elements in the list must be generated when the Canvas rebuild their geometry, arrangement, and analyzed.


Simple Scroll View element pooling - simple elements Scroll View pool

The simplest way to implement object pooling with a Scroll View while also preserving as much of the native convenience of using Unity’s built-in Scroll View component is to take a hybrid approach:

To lay out the elements in the UI, which will allow the layout system to properly calculate the size of the Scroll View’s content and allows scrollbars to function properly, use GameObjects with Layout Element components as “placeholders” for the visible UI elements.

Then, instantiate a pool of visible UI elements sufficient to fill the visible portion of the Scroll View's visible area, and parent these to the positioning placeholders. As the Scroll View scrolls, reuse the UI elements to display content that has scrolled into view.

This will substantially cut down on the number of UI elements that must be batched, as the cost of batching only increases based on the number of Canvas Renderers within a Canvas, not the number of Rect Transforms.

Most convenience way to achieve Scroll View original object pool easiest Unity while preserving the built-in Scroll View components is to use a hybrid approach:

In the UI layout elements, which will allow the system to calculate the content layout Scroll View correct size, scrollbar and allows normal operation, the game object using Layout Element mount assembly as visible UI elements "placeholders (placeholders)."

Then, examples of Scroll View sufficient to fill the visible portion of the visible UI element visible region, and is set to the parent object a good positioning placeholders. When scrolling Scroll View, reuse UI element to display content to scroll the viewport.

This will greatly reduce the number of UI elements must be batch, because the overhead is only based on the number of batch growth Canvas Renderer in the Canvas, rather than the number of Rect Transform.


Problems with the simple approach - simple solutions to problems

Currently, whenever any UI element is reparented or has its sibling order changed, that element and all of its sub-elements are marked as “dirty” and force a rebuild of their Canvas.

The reason for this is that Unity has not separated the callbacks for reparenting a transform and altering its sibling order. Both of these events will fire an OnTransformParentChanged callback. In the source of Unity UI’s Graphic class (see Graphic.cs in the source), that callback is implemented and invokes the method SetAllDirty. By dirtying the Graphic, the system ensures that the Graphic will rebuild its layout and vertices before the next frame is rendered.

It is possible to assign canvases to the root RectTransform of each element within the Scroll View, which will then confine the rebuild to only the reparented elements and not the entire contents of the Scroll View. However, this tends to increase the number of draw calls needed to render the Scroll View. Further, if the individual elements within the Scroll View are complex and consist of more than a dozen Graphic components, and particularly if there is a significant number of Layout components on each element, then the cost of rebuilding them is often high enough to noticeably reduce the frame rate on lower-end devices.

If a Scroll View UI element does not have a variable size, then this full recalculation of layout and vertices is unnecessary. However, avoiding this behavior requires the implementation an object pooling solution based on position changes instead of parent or sibling-order changes.

Currently, when any UI element reset parent, or hierarchical ordering conversion when the element and all child elements will be labeled "Dirty", and will be forced to rebuild its Canvas.

The reason for this is that there is no separation Unity reset and change its parent-level sort of pullback. These events will trigger a callback call OnTransformParentChanged. In the Graphic class UGUI source in (Graphic.cs see the source code of the script), and implemented to achieve this callback method SetAllDirty. Graphic by standard Dirty, the system can ensure that the layout and Graphic reconstructed before the next frame rendering vertices.

Canvas may be allocated to the root Scroll View RectTransform each element, which would limit the scope of the reconstruction occurs only in the reset element's parent Scroll instead of the entire content View. But it will also increase the number of drawcall need to render Scroll View. Furthermore, if the individual elements Scroll View is complex and contains a dozen Graphic components, in particular on each element contains a large number of Layout assembly rebuild overhead will also often be reduced significantly to the high end equipment frame rate.

If the size of a UI element Scroll View is immutable, then fully recalculate the layout and the vertex is unnecessary. However, the solution to avoid this problem is the need to achieve the target pool based on changing the position of the parent rather than re-set or change the hierarchical order.


Position-based Scroll View pools - based on a change in position Scroll View pool

In order to avoid the problems described above, it is possible to create a Scroll View that pools its objects by simply moving the RectTransforms of its contained UI elements. This avoids the need to rebuild the contents of the moved RectTransforms if their dimensions are not altered, significantly improving the performance of the Scroll View.

To accomplish this, it is generally best to either write a custom subclass of Scroll View or to write a custom Layout Group component. The latter is generally the simpler solution, and can be accomplished by implementing a subclass of Unity UI’s LayoutGroup abstract base class.

The custom Layout Group can analyze the underlying source data to examine how many data elements must be displayed and can resize the Scroll View’s Content RectTransform appropriately. It can then subscribe to Scroll View change events and use these to reposition its visible elements accordingly.

To avoid this problem, only to create a mobile RectTransform UI elements comprising the target storage pool. This avoids the rebuild content size unchanged by moving RectTransform, significantly improves the performance of Scroll View.

To do this, the component is usually best to Layout Group Scroll View subclass to write a user-defined and write a user-defined. The latter is usually more simple solution, it can be accomplished by LayoutGroup abstract base class to implement UGUI.

LayoutGroup user-defined metadata can be analyzed to check how much of the underlying data elements to be displayed, and may re-set the content of Scroll View RectTransform suitable. You can also listen Scroll View onValueChanged event and reset the position corresponding to the visible elements.


6.Other UI Optimization Techniques and Tips - UI optimization techniques and other tips

Sometimes there is just no clean way to optimize a UI. This section contains a handful of suggestions that may help improve UI performance, but some are “unclean” structurally, may be difficult to maintain, or may have ugly side effects. Others may be workarounds for behavior in the UI intended to simplify initial development, but also make it relatively simple to create performance problems.

Many times a simple and there is no way to optimize the UI. This section contains some suggestions may improve UI performance, but some are not structurally simple, or difficult to maintain, or have some bad marginal effect. Other UI are some of the initial development becomes simple act of solutions, but will be more likely to cause some performance issues.


Many times a simple and there is no way to optimize the UI. This section contains some suggestions may improve UI performance, but some are not structurally simple, or difficult to maintain, or have some bad marginal effect. Other UI are some of the initial development becomes simple act of solutions, but will be more likely to cause some performance issues.


RectTransform-based Layouts - based on the layout of RectTransform

Layout components are relatively expensive, as they must recompute the sizes and positions of their child elements each time they are marked dirty. (See the Graphic rebuild section of the Fundamentals step for details.) If there is a relatively small and fixed number of elements within a given Layout, and the Layout has a relatively simple structure, it may be possible to replace the Layout with a RectTransform-based layout.

By assigning the anchors of a RectTransform, the RectTransform’s position and size can be made to scale based on its parent. For example, a simple two-column layout can be achieved with two RectTransforms:

  • The left column’s anchors should be X: (0, 0.5) and Y: (0, 1)
  • The right column’s anchors should be X: (0.5, 1) and Y: (0, 1)

The computations of the size and position of the RectTransform will be driven in native code by the Transform system itself. This is generally more performant than relying on the Layout system. It is also possible to write MonoBehaviours that set up a RectTransform-based Layout. However, this is a relatively complex task and lies beyond the scope of this guide.

Layout component performance overhead is relatively expensive because they must recalculate their size and position of child elements each time it marks Dirty (For details, see Fundamentals Graphic rebuild part section). If the given number of elements in the Layout relatively small and fixed number, and Layout relatively simple structure, can be used to replace Layout based RectTransform Layout.

, RectTransform position and size can be scaled based on the distribution by a parent RectTransform anchor. For example, two RectTransform be able to achieve a simple layout with two columns:

The left column of the anchor should be X: (0,0.5) and Y: (0,1) (covering the left side of the screen)

Anchor right column should be X: (0.5,1) and Y: (0,1) (covering the right of the screen)

Calculate the size and position by itself RectTransform Transform drive system native code. This is usually more efficient than relying Layout System. Write RectTransform of MonoBehaviour script based on layout also possible. However, this is a relatively complex task, but also beyond the scope of this guide.


Disabling Canvases - 禁用Canvas

When showing or hiding discrete portions of a UI, it is common to enable or disable the GameObject at the root of the UI. This ensures that no component in the disabled UI receives input or Unity callbacks.

However, this also causes the Canvas to discard its VBO data. Re-enabling the Canvas will require the Canvas (and any Sub-canvases) to run the rebuild and rebatch processes. If this happens frequently, the increased CPU usage can cause the application’s frame rate to stutter.

One possible, but hacky, workaround is to place the UI to be shown/hidden onto its own Canvas or Sub-canvas and then to merely enable/disable the Canvas component on this object.

This will cause the UI’s meshes to not be drawn, but they will remain resident in memory and their original batching will be preserved. Further, no OnEnable or OnDisable callbacks will be invoked in the UI’s hierarchy.

Note, however, that this will not disable any MonoBehaviours within the hidden UI, and so these MonoBehaviours will still receive Unity lifecycle callbacks, such as Update.

To avoid this issue, MonoBehaviours on UIs that will be disabled in this manner should not directly implement Unity’s lifecycle callbacks, but should instead receive their callbacks from a “Callback Manager” MonoBehaviour on the UI’s root GameObject. This “Callback Manager” can be informed whenever the UI is shown/hidden, and can ensure that lifecycle events are propagated or not propagated as necessary. Further explanation of this “Callback Manager” pattern is beyond the scope of this guide.

When a display or hide the UI discrete portions, typically enable or disable the root object of this game UI. This ensures that the disabling of the UI component receives no input or execution Unity callback function.

However, this will result in its discarded Canvas VBO (vertex buffer objects) data. Will re-enable Canvas Canvas (including all sub Canvas) and rebatch force a rebuild process. If this happens very frequently, increase the CPU usage will cause frame rate Caton application.

One possible approach is to show and hide the UI control in its Canvas Canvas and son, only is enabled or disabled child or related to the Canvas Canvas Canvas Renderer component (does not mean really Canvas Renderer component, but to rely on Canvas Renderer component image, text components, etc.).

This UI will not be drawn on the grid, they will remain resident in memory, their original batch will be saved. In addition, in the hierarchy of the UI will not have OnEnable or OnDisable callback function to perform.

However, note that this method will not eliminate the graphics GraphicRegistry in the UI, so they will still appear in the list of components Graphic Raycast to be examined. This method does not disable any script MonoBehaviour hidden in the UI, so these scripts will accept MonoBehaviour Unity lifecycle callbacks, such as Update.

To avoid this problem, in this way will be banned MonoBehaviour script on the UI should not be implemented directly Unity lifecycle callback function, but should be received by mounting the "Callback Manager" MonoBehaviour script on the root UI object game Callback. Whenever the UI to be displayed and hidden and they will inform Callback Manager, which will ensure the spread of life-cycle events as needed or do not spread. For further explanation Callback Manager mode is beyond the scope of this guide.


Assigning Event Cameras - Camera assign an event

If using Unity’s built-in Input Managers alongside Canvases set to render in the World Space or Screen Space – Camera modes, it is important to always set the Event Camera or Render Camera property, respectively. From script, this is always exposed as the worldCamera property.

If this property is not set, then Unity UI will search for the main camera by looking for Camera components attached to GameObjects with the Main Camera tag. This lookup will occur at least once per World Space or Camera Space Canvas. As GameObject.FindWithTag is known to be slow, it is strongly recommended that all World Space and Camera Space Canvases have their Camera properties assigned at design-time or initialization time.

This issue does not occur for Overlay Canvases.

If you use the built-Input Manager and Unity Canvas rendering mode to World Space or Screen Space - Camera mode, always set the event were the camera and render camera is very important. In the script, it is always as worldCamera public property.

If this property is not set, it will hang there UGUI camera object game to find the main camera through the main camera label, this at least every World Space Camera Space or the occurrence of Canvas will find. GameObject.FindWithTag notoriously slow, so it is strongly recommended that all World Space and the Canvas Camera Space Camera will set its properties in the design or initialization.

This problem does not occur on the Canvas Overlay.

发布了13 篇原创文章 · 获赞 1 · 访问量 415

Guess you like

Origin blog.csdn.net/u011366226/article/details/104730480