Search code examples
unity-game-engineyamlsceneprefab

Should I include the Canvas parent GameObject in a UI prefab in Unity


I have four different Canvas elements in my Unity scene. This organizes them by concern, but also improves performance since I don't have to rebuild all the elements if I "dirty" one of them. I want to create prefabs of each so I can reuse them across the game, and also so there are less elements in my scene file (I have yet to figure out why Unity doesn't re-organize YAML to match the scene order and hierarchy. Currently I can see no reason and it makes source control a huge pain).

So, my question: Should I include the Canvas as the parent GameObject in the prefab, or should I make the first child the prefab (see image)? I see two perspectives:

  1. On one hand it's nice to scan the list of elements in the root of the scene and see the blue objects and know they are automatically replicated across scenes. Plus, the more object stored in the prefab then there will be less to pollute my YAML file.
  2. On the other, with a Canvas Scalar script on the parent, the sizes inside the prefab are going to be updated every time I change the resolution / platform and I've read it's not good always update them outside of prefab mode. The other issue is the fact that UI elements usually have a lot of external references to update text and so forth.

hierarchy


Solution

  • After a lot more research I've come to some conclusions about the answer:

    1. As stated in this talk at Unite 2017, isolating UI element "islands" by concern AND how often they are updated will keep the UI from affecting performance. The video also states it is fine to use multiple Canvases inside other Canvases to achieve this goal.
    2. If you add a prefab whose values are updated from outside the prefab they will appear as "overrides" to that prefab. This includes if you link to elements outside the prefab from within it and vice versa (see image). Importantly, it is not possible to apply these overrides to the prefab, and that's kind of the point. Unity accepts that these changes will happen and this is how it deals with them without breaking the prefab or the scene.

    So the answer is yes, it's no problem to include the Canvas parent in the prefab, and you can even organize it inside other Canvas so they all inherit the same settings. Further, since the more code stored in prefabs decreases the extra (unorganized) identical code in the .unity YAML file (in my case from 17,000 lines to just less than 5000!) then this is the recommended way.

    overrides

    outside reference