Can UI be done programmatically so it can be reused easily?

I am not sure if I can design UI programmatically in Unity. In app development, I usually write UI programmatically and store key UI structures in Constant or Utils, so when I need UI to create other apps I will just copy paste the UI and adjust some area to fit the needs of the new apps.
Doing UI in Unity is like doing UI in Swift storyboard, or Ui panel on the right side of android studio, even though the Prefab can be copy paste into different projects, I still have to click different components and check the detail elements in each of them. It’s easy to miss something.

In programmatic design, all codes are placed in front of me. It’s easier to adjust layout, spacing, size, etc. from just one screen, or few screens. and no need to worry about the strange saved/resaved bugs in Unity.

You could build a “base” UI template in one project and import it into future projects. If you are using UI Toolkit, it would be easy. Just build your base template using the UXML and USS with an accompanying C# script. Then import those three files into your current project.

UI Toolkit API

You can actually create an entire UI in both the current UI method we’re using in the course (Canvases) and the new UIElements system, without having a single GameObject in the scene file or even a prefab.

That being said, it’s some work. It’s easier in UIElements because you can define the layout using UXML (basically XML, but Unity insists on their own flavor). We have a short course introducing UIElements, which covers using it for Editor windows, but it’s easily adaptable to use as in game UI.

For the standard UI, you’ll need to create a Canvas (or at least have a reference to one), and then add the elements with statements… i.e. create an image, set it’s RectTransform, set it’s sprite property, etc.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms