UI Manager
About
When we were working on Fishy Business I was getting tired of writing the same UI code over and over. So I decided to create a UI Manager that would handle all the UI in the game. After creating the system for the game I decided to make it more generic, so I could use it in future projects.
The system consists of 3 different scripts:
- ViewManager, responsible for managing all the views.
- View, a game view (e.g. hud, pause menu, etc.)
- ViewComponent, an element withing a game view (e.g. Money UI)
View Manager
The View Manager is a system that manages the different views in the game. It handles
transitions between different in-game screens and maintains a history for easy backtracking.
You can open views by calling ShowView
with either the view's type or a specific
view instance. When using ShowView
, you can choose the option to record the current
view in the history stack, allowing for easy backwards navigation.
private readonly Stack<View> viewHistory = new();
private View activeView;
public void ShowView<T>(bool saveInHistory = true)
{
foreach (View view in allViews)
{
if (view is not T)
continue;
if (activeView != null)
{
if (saveInHistory)
{
instance.viewHistory.Push(activeView);
}
activeView.Hide();
}
view.Show();
activeView = view;
}
}
View
The View class is the base class for all views in the game. It contains methods for showing and hiding the view. Each view has a reference to all the components that need to be enabled when the view is shown. Let's say you have a money UI element, this element will be disabled when the view is hidden and enabled when the view is shown. This way you can re-use the same UI elements in different views.
View whole script
[SerializeField] private ViewComponent[] viewComponents;
public virtual void Show()
{
gameObject.SetActive(true);
ShowViewComponents();
}
public virtual void Hide()
{
gameObject.SetActive(false);
HideViewComponents();
}
View Component
The ViewComponent class is the base class for all components that are part of a view. It contains methods for initializing, showing and hiding the component.
View whole script
public abstract class ViewComponent : MonoBehaviour
{
public virtual void Initialize() { }
public abstract void Show();
public abstract void Hide();
}