The QuizU UI Toolkit sample: Now updated for Unity 6 (Post 1)

How we made the UI Toolkit sample QuizU: A 7-part series

Update: QuizU, a UI Toolkit sample for programmers, is now updated to Unity 6.1. You can download the latest version of QuizU from The Unity Asset Store.

The first version of QuizU was released in the fall of 2023. For those who haven’t tried it already, QuizU, is a sample of an interactive quiz application that shows how UI Toolkit components can work together, leveraging various design patterns, in a small but functional game, complete with multiple screens and game flow management.

This post is the first in a series of articles that provide additional information on how we implemented the project using UI Toolkit. The sample is just a simple quiz game mechanic but the intent is to show and teach implementation techniques that you can use in your own projects.

QuizU + other UI Toolkit resources for Unity developers

QuizU was created mainly with programmers in mind, explaining UI Toolkit concepts and tools from a developer perspective. If you are more interested in the “frontend” side of things we also have UI Toolkit sample – Dragon Crashers – a slice of a full-featured interface added to the 2D project Dragon Crashers, using the Unity 6 UI Toolkit workflow at runtime.

Additionally, you might also find value in one of our new e-books, UI Toolkit for advanced Unity developers (Unity 6 edition).

Download QuizU from the Unity Asset Store, running on Unity 6.1 to follow along.

The other articles in this series are:
Post 2: QuizU: Managing menu screens in UI Toolkit
Post 3: QuizU: State patterns for game flow
Post 4: QuizU: The Model View Presenter pattern
Post 5: QuizU: Event handling in UI Toolkit
Post 6: QuizU: Vector API
Post 7: QuizU: UI Toolkit performance tips

Wilmer Lin is the main creator of the demo and instructional content in this article series. Wilmer is the author of a number of our e-books. He’s a 3D and visual effects artist with over 15 years of industry experience in film and television, now working as an independent game developer and educator. We also worked with our UI Toolkit R&D team and several internal experts in bringing all of this material together.

Let’s dive into our first article explaining QuizU.

What can you learn from the QuizU sample?

QuizU implements common design patterns and event-driven architecture. Think of it as a study tool or a starter project for a larger application. And don’t forget to play the game, too – it’s a fun way to test how well you know Unity or perhaps prepare for a Unity certification.


Test your knowledge in QuizU or use it as a starting point for creating your own quiz game.

Key features

UI Toolkit demos
QuizU is designed to help make it easier to get started or take the next steps using UI Toolkit. The project provides 10 small, digestible samples that demonstrate different aspects of UI Toolkit.

A mini quiz game with UI management
The sample project showcases a UI-centric quiz game mechanics that implements various patterns for managing UI and game flow. It offers practical insights into handling multiple UI screens or breaking a large UI into smaller displays. The game part includes a few quizzes that are inspired by official Unity certification questions (if you are interested in testing your knowledge).


The QuizU project is a UI Toolkit-based game sample.

Design patterns
QuizU also showcases several core design patterns, including the usage of the state and model-view-controller (MVC) design patterns. These can help anchor your game architecture, so new features don’t break your existing application.

Event-driven development
The project also promotes loose coupling for scalability and testability by having game objects and systems to communicate using events.

Each scene in the demo illustrates a specific UI Toolkit capability

The QuizU project in Unity UI Toolkit offers a variety of standalone demo scenes, each serving as a bite-sized showcase of a specific UI Toolkit topic.

Think of these scenes as a set of recipes while exploring the UI Toolkit. Here’s a brief sampling of what’s inside:

  • UXML and Visual Trees: UXML files form a hierarchical structure of UI elements. These visual trees serve as a blueprint for your user interface.

  • Flexbox: The Flexible Box Layout Model (flexbox) provides an efficient layout model for arranging UI elements dynamically within a container.

  • Unity Style Sheets (USS): USS allows developers to customize UI elements with predefined styles. Reskinning your UI is just a matter of swapping style sheets.

  • UQuery: UQuery simplifies the process of searching through a complex hierarchy of UI elements, enabling seamless navigation to specific UI components within the visual tree.

  • Pseudo-classes: Pseudo-classes can be used to create interactive and animated UI elements with minimal extra code, adding extra ‘juice’ to your visual interface (e.g. enlarging a button when hovering over it or changing a text field color after selection).

  • UI Toolkit Event System: UI Toolkit has its own complementing event system, designed to handle your UI’s clicks, changes, and pointer input, even across complex hierarchies.

  • Manipulators: Encapsulating related event callbacks into a single class, a manipulator promotes reusability and makes it easier to define user interactions (e.g. a click-and-drag manipulator for an inventory system, a gesture manipulator for a pinch-to-zoom effect, etc.).

  • Custom Controls: Unity 6 simplifies the creation of custom controls using the UxmlElement attribute. Now, custom VisualElements can be directly deployed within UXML and the UI Builder (without the previous UxmlFactory and UxmlTraits syntax), making them more reusable across your various UIs.

  • Data Binding: This Unity 6 feature allows your UI elements and your data sources to communicate more directly. This means they can update more easily at runtime with improved user interaction within UI Toolkit.

  • Localization: The demo showcases how to set up multiple languages and regional settings directly within the UI Toolkit. Text and other locale-sensitive data within the application can then update during gameplay.

  • Vector API: UI Toolkit allows you to create complex shapes and vector graphics using a script. Use paths, fills, and strokes to render lines, curves, arcs, and custom shapes without the need for external textures.

As you dive deeper into the UI Toolkit, use these demo scenes as a source of inspiration or a reference guide. Then, you’ll be ready to create your own rich, interactive user interfaces.

The mini-game

While the mini-sample demos can help you understand specific topics in UI Toolkit, we’ve also compiled many of these techniques into a mini-game so you see how UI Toolkit fits into a more complete project.

Select a Quiz topic and then test your own Unity knowledge.


Test your Unity knowledge in QuizU.

The visual style is minimalistic because we want you to focus on the mechanics of putting the UI together without getting lost in the design details. This way you can see clearly how the UI elements combine into a cohesive user interface. It also makes it easier for you to reskin and apply your own theme using the project as a boilerplate template.

To help you manage your UI Toolkit-based interfaces, the project also demonstrates a stack-based navigation system for handling multiple screens. The third article in this series explains this navigation system in detail, but for now, here are its main components in brief:

  • Several Visual Tree Assets combine into a single UXML in UI Builder (UIScreens.uxml). Each visual tree corresponds to one UI screen in the application. A UI Document component reads this master UXML and then generates the relevant on-screen UI from that.

  • A stack-based state machine – or “screen stack” – manages the UIs. Each screen is a fullscreen UI under the control of a UIManager class and is treated as a layer of a stack. Think of it like working with a pile of plates: You can only interact with the top plate, and to get to a plate beneath the top one, you have to remove plates on top of it. The last plate you put on is always the first one you take off. This is also referred to as the Last-In, First-Out (LIFO) principle.

  • When a new screen opens, the UI Manager pushes onto the top of the stack and makes it the active state. When a screen is closed, it pops off the stack. This is a simple and effective way to navigate between modal screens.

  • More complex UI Screens can be broken into smaller visual parts. The main Game Screen is a composite of several smaller displays. Each smaller “sub-screen” is handled independently; it can interact with the other smaller sub-screens or with the main UI Screen. This keeps everything more modular and reusable.

Whether you are creating a menu system for a game jam or developing a more complex project, this stack-based navigation system can provide a flexible and scalable framework for managing multiple UI screens.

QuizU: Exploring the demo scenes

If you are new to UI Toolkit

UI Toolkit offers a comprehensive suite of features and tools to support you in building runtime UIs for game applications and Editor extensions. Compared to the older UGUI system, UI Toolkit provides a new workflow and architecture that offers several improvements over UI development, however, with a steeper learning curve. But the benefits it provides are significant, including:

  • Scalability and Performance: UI Toolkit is designed to be more efficient and performant, particularly for large projects with complex user interfaces.

  • Style Separation: UI Toolkit separates styling from the logic using USS (Unity Style Sheets), similar to CSS in web development. This can make your UI code cleaner and easier to maintain. Designers can iterate on aesthetics without touching any code.

  • UXML Templates: You can define reusable templates and instantiate them in your code. This can make it easier to design complex UI layouts while making more modular components reusable across the project

  • Unified support for runtime and Editor: The UI Toolkit works in both the Unity Editor and at runtime, allowing you to use the same system for creating custom Editor windows and in-game UI.

The QuizU sample includes several standalone scenes that illustrate key concepts within the UI Toolkit. Each one represents a specific technique or feature. Consider these scenes as a set of recipes to inspire and guide you as you evaluate UI Toolkit for your next project.

Demo selection

Navigate to the Demo Selection Screen via the Main Menu screen, or if you prefer, disable the bootloader scene (Quiz > Don’t Load Bootstrap Scene on Play) and load each scene manually.

Let’s break down some concepts highlighted in these demo scenes.


Select a demo from the Demo Selection Screen.

UXML and visual trees

UXML, or Unity XML, is the markup language used to structure and organize user interfaces in UI Toolkit. It provides a blueprint for constructing a visual tree, a hierarchy of UI elements. Every element declared in a UXML file corresponds to one node in the visual tree.

UXML files can also serve as reusable templates for UI elements, much like prefabs do for GameObjects. When a UXML file (or template) is loaded or instantiated, a corresponding visual tree is created in memory.

Consider UXML files as building blocks for UI structures and controls. UXML supports nesting, allowing your team members to work on individual UXML files and then combine them into a master hierarchy. This can prevent merge conflicts and promote modularity.

In our demo /Demos/1_UXMLVisualTreeDemo/UXMLVisualTreeDemo we demonstrate a simple use case with common elements like Labels, Text Fields, Buttons, and Sliders. It also features a GroupBox to group elements visually with a built-in border and label.


The demo introduces the visual tree hierarchy.

Flexbox rules and layout

Flexbox is a layout model inspired by web technologies that allows for the arrangement of UI elements within a container, even when their sizes are unknown or dynamic.

These rules allow for responsive design, adapting designs to various screen sizes and resolutions. Both row and column direction, control of the wrapping of elements, and managing the growth and shrinkage of elements based on available space are all possible with flexbox rules.

Building on the concept of visual trees in UI Toolkit, visual elements can act as flex containers using the flexbox layout rules. When functioning as parents, these containers can help organize child elements in an efficient manner.

Our Flexbox demo scene /Demos/2_FlexboxDemo/FlexboxDemo walks you through the basic rules of working with a flex container and its children. For more information on element positioning, see the UI Toolkit Layout Engine documentation.


Adjusting the Flexbox properties.

USS styles

Unity’s UI Toolkit provides a flexible system of styling using USS (Unity Style Sheets). Similar to their CSS equivalents, USS style sheets allow you to change the appearance of your elements by swapping predefined styles.

In the demo scene /Demos/3_USSStylesDemo/USSStylesDemo, compare the stylesheet code for a default button and several variants with different styles applied. Modifying font styles, colors, sizes, and positions is as easy as applying .uss files.


Change an element’s appearance through USS styles

UQuery

UQuery is a feature that simplifies finding elements within a complex hierarchy in UI Toolkit. Similar to how jQuery simplifies DOM traversal in web development, UQuery simplifies hierarchy traversal in Unity’s UI Toolkit.

This demo scene /Demos/4_UQueryDemo/UQueryDemo demonstrates its usage, by providing a query selector which highlights the selected UI elements, making it easier to interact with specific UI components in the visual tree.


UQuery can make it easy to search through a complex hierarchy.

Pseudo-classes

Pseudo-classes are special selectors that target UI elements based on their state or certain characteristics, such as :hover, :active, and :focus, similar to their function in CSS.

This demo scene /Demos/5_Pseudo-classesDemo/Pseudo-classesDemo shows the basic usage of pseudo-classes for simple animations and interactivity. With a few extra styles and no extra code in most cases, we can make the UI elements visually respond to the user’s input.


Pseudo-classes target elements based on their state.

USS Transitions

USS transitions allow you to modify UI properties over time, making your UI come alive with simple animations.

The demo /Demos/5_Pseudo-classesDemo/Pseudo-classesDemo provides some simple examples of how to add USS transitions for improving the visual feedback to the user.


USS transitions provide an easy way to animate your UI for improved visual feedback.

Events

UI Toolkit comes with its own event system, designed to cater to user interface events (e.g. click events, change events, pointer/mouse events, etc.).

Note that this UI Toolkit event system can complement other events in your application, such as the Input System events or System delegates. While the UI Toolkit concentrates on UI-specific actions, the Input System can broadly handle raw device-level inputs. Standard .NET events provide a general way to interact with anything else. You can connect one type of event to another for the desired behavior.

The demo scene /Demos/7_EventsDemo/EventsDemo shows how separate elements – a Slider, Button, and TextField – can communicate using UI Toolkit events.


Create interactions with the UI Toolkit event system.

Event dispatch and propagation

The UI Toolkit event system operates through a system of event propagation that allows events to traverse the visual tree hierarchy. The event starts at the root of the VisualElement tree and travels down toward the target element. The demo /Demos/8_EventDispatchDemo/EventDispatchDemo shows how an event trickles down, reaches its target, and then bubbles up. Use event dispatch to your advantage when setting up a container with several child elements.


Events can propagate through the visual tree.

Manipulators

A manipulator is a utility class that can help you handle specific types of user interaction with UI elements.

Imagine click-and-drag interaction or a pinch-to-zoom operation. These can involve several related event callbacks to work properly – the response to the mouse click, the dragging action, and then the mouse release. Manipulators allow you to bundle those event callbacks together for easier management.

Once the manipulator is created, it’s reusable and ready to add to your UI elements. Simply attach them to any elements that need the functionality.

In summary, a manipulator essentially streamlines setting up that user interaction, so you don’t have to handle each callback one by one.

This demo /Demos/9_ManipulatorDemo/ManipulatorDemo showcases a custom manipulator that makes an element draggable with the mouse pointer. Making game pieces or floating windows is then just a matter of adding the example manipulator to the parts of your UI that need that specific user interaction.


Manipulators can be used for creating interactive behavior for your UI, such as the draggable elements in this example.

Custom controls

UI Toolkit also allows you to create custom controls – illustrated in scene Demos/10_CustomControlsDemo/CustomControlsDemo – that extend the functionality of the base UI Toolkit classes, giving you additional features or behaviors specific to your application’s needs.

UI Toolkit’s integration of the UxmlElement attribute in Unity 6.1 simplifies custom control creation and removes the need for the previous UxmlFactory and UxmlTraits classes. This allows you to instantiate custom components directly within UXML and makes them accessible from the UI Builder’s library.

To create a custom control, define a new C# script that inherits from VisualElement or another appropriate subclass that matches the desired functionality. To integrate your custom control available within the UI Builder, apply the UxmlElement attribute to your class. Ensure that your custom element is declared as a public partial class.

Your custom control will appear under the Custom Controls category in the UI Builder, where you can drag and drop it into your project’s UI hierarchy.

Apply the UxmlAttribute to properties you wish to expose in the UI Builder’s Inspector when the control is selected.


Custom UxmlAttributes appear in the Inspector.

Effective custom controls like a slide toggle are abstract, self-contained, and ideal for promoting code reuse and simplifying maintenance, whereas application-specific elements like menu bars are less suitable due to their dependency on other components.

For creating a custom slide toggle, inherit from BaseField to encapsulate behavior and appearance, and use the UxmlElement attribute to make it available in UXML and UI Builder. Construct the visual hierarchy with child elements for the background and knob, styled with USS classes. Manage user interactions through event handling like clicks and key presses.

The provided slide-toggle example demonstrates setting up a custom control, allowing interaction through mouse clicks or key presses to toggle its active state.


Extend the functionality of the base UI Toolkit classes with Custom Controls

Vector API

UI Toolkit in Unity 6.1 provides a Vector API, a powerful and flexible way to generate custom 2D visual content within UI elements.

Inspired by the HTML Canvas API, it allows you to draw vector graphics – such as lines, arcs, and shapes – directly onto visual elements using simple commands without needing textures, images, or shaders.

In the demo /Demos/11_VectorAPIDemo/VectorAPIDemo we showcase several use cases including how to create a virtual “pen” that you can move and draw with by issuing commands. The Vector API has the ability to create both simple and complex shapes with holes or complex fill patterns.


The Vector API is a powerful and flexible way to generate custom 2D visual content within UI elements.

Databinding

Data binding is a technique that connects your app’s data to its UI elements, keeping them synchronized automatically.

This removes the need for manual updates as the UI can dynamically reflect changes in the data. For example, a health bar can update in real time as the player’s health changes.

Separating the View (UI) from theModel (data) is a core principle of UI architecture. This decoupling makes each layer of the application flexible and modular but requires that they sync to one another.

Unity 6 simplifies this synchronization process using the runtime data binding system. You can set up bindings visually in the UI Builder using UXML or at runtime with C# scripts. The UI Builder generates Bindings code blocks in UXML, which you can edit directly if needed. C# scripting, on the other hand, allows for runtime adjustments through the API.

Our demo /Demos/12_DataBinding/DataBinding provides a few ways of implementing runtime data binding in practice using player health bars as examples.


Data binding is a technique that connects your app’s data to its UI elements, keeping them synchronized automatically.

Localization

The Localization package provides tools for adding support for multiple languages and regional variants to your application (for example, supporting text in multiple languages or culture-specific Assets such as audio or textures).

It’s now also integrated with UI Toolkit, which simplifies enabling multi-language support and region-specific content variations.

One of the key concepts is the concept of setting up a Locale to represent a language and a set of regional variations, such as currency and number formatting. This way your content isn’t fixed – it can change dynamically to a different language with just one click.

In our demo /Demos/13_Localization/Localization we show how to set up text and asset localization for different languages, customize data binding, and switch between Locales at runtime with UI Toolkit.


The Localization package provides tools for adding support for multiple languages and regional variants to your application.

Continuing with UI Toolkit

We hope these demo scenes inspire you with new ideas, or serve as references for specific techniques and patterns, as you continue to build your understanding of UI Toolkit.

We also suggest exploring the comprehensive examples in the documentation. These showcase how to assemble elements into functional UIs for both runtime and Editor scripting.

Design patterns

Game programming patterns are reusable solutions to common problems in software development. They can help streamline your code, making it more readable and maintainable.

The QuizU game implements several of these patterns, including:

  • The state pattern allows an object to alter its behavior when its internal state changes. This pattern can reduce a more complex object into a predetermined set of states. The QuizU project uses a SequenceManager and UIManager that show different types of state machines.

  • The model-view-presenter (MVP) pattern maintains a strict separation between the app’s data (Model), UI (View), and the controlling intermediary that binds the two (Presenter). This improves readability and maintainability.

  • The observer pattern can help decouple objects to reduce their interdependencies. This can improve testability and reduce class size. QuizU uses System.Action delegates as well as the UI Toolkit event system.

We’ll look in detail at each of these patterns in the next articles.

Learn more in the guide Level up your code with design patterns and SOLID. This e-book provides insights into the SOLID principles and various design patterns, introducing practical examples in Unity.

Event-driven development

The sample project uses the observer pattern to control how objects in the sample project communicate. In QuizU, almost everything that “happens” in the application is the result of an event.

Since this is an educational sample, and design patterns shouldn’t be used just for their own sake, it demonstrates one possible approach to structuring your code. Using static events can let objects pass messages without directly referencing each other because they are globally accessible from anywhere in the application, provided they have the appropriate access level. This decoupling makes your components easier to maintain and debug – without affecting the rest of the game’s systems. Static events add a layer between the publishing objects that broadcast the signals and the objects which may be listening.

One benefit of event-driven development is that you can reduce reliance on the singleton pattern. Singletons can be convenient in smaller applications due to their global accessibility and persistent states; however, they can cause problems in larger, complex systems. Singletons often produce tightly-coupled code, making it difficult to debug or extend. Plus, the ease of access that singletons offer often leads to misuse or overuse.

Instead, event-driven development uses the publish-subscribe model for messaging. Events can allow for modular components that can be tested more easily.


Different parts of the application use events to communicate. You can find the events in the Scripts/Events folder.

Want to input your quiz answer, play a sound or queue up the next question? You can implement them as events. Invoke messages using the static event class and pass along any required data as a payload. Any object can listen for specific events and execute any handlers in response.

The events in QuizU fall into the following categories, with separate classes for each:

  • Game Events (\Quiz\Scripts\Events\GameEvents.cs) manages the core game flow. They update questions, handle user-selected answers, display feedback, and manage game states (start, pause, abort, win, lose).

  • Level Selection Events (\Quiz\Scripts\Events\LevelSelectionEvents.cs) allows the user to choose a quiz from the Level Selection Screen.

  • Scene Events (\Quiz\Scripts\Events\SceneEvents.cs) manages loading, unloading, and progress updates of different scenes in the game.

  • Settings Events (\Quiz\Scripts\Events\SettingsEvents.cs) handles changes to master, SFX, and music volume.

  • UIToolkit Events (Quiz\Scripts\Events\UIEvents.cs) maintains a separate set of events in order to interact with UI elements, such as buttons, sliders, and input fields. They process everything from clicks and drags to value changes, and can be used to trigger updates or transitions in the game.

By dividing the game logic into these distinct event classes, QuizU can handle complex game state transitions and interactions in a clean and organized way. For example, when a user selects an answer, the AnswerSelected event is triggered in the GameEvents.cs. That, in turn, updates the game state and UI in UIEvents.cs.

This breaks the application into small “islands of code” that can operate more independently from each other. UI, game logic, settings – they all just need to listen for events and react accordingly.

BootloadScreen

The demo project uses a couple of common techniques to help start the game application in a consistent and predictable state. One of these is a Scene Bootstrapper (or bootloader) which is an editor extension script (/Quiz/Scripts/Editor/SceneBootStrapper.cs) responsible for setting up the game’s initial state.

It uses the [InitializeOnLoad] instruction to ensure that whenever you press Play in the Editor, you start from the bootstrap scene even if you’re currently editing a different scene. This initialization code is separate from the game logic and ensures that all dependencies are set up correctly for the objects in the scene.

If your Unity application spans several scenes like QuizU, the bootloader can force loading a specific bootstrap scene, which is the first scene from the Build Settings. When exiting Play mode, the Editor reloads the previous scene.

Another component in the bootstrap scene, the Sequence Manager (more information is provided on this component in an upcoming article), can then instantiate essential prefabs on scene load. In this specific demo project, everything needed to create the game is a prefab, including a camera, SplashScreen, UI menus, and a SceneLoader.

The SceneLoader then additively loads (and unloads) any gameplay scenes as needed. In most cases, these scenes are composed of prefabs.


The Bootloader initializes dependencies to control flow of project scenes.

Project scenes

Each mini-game level is a separate Unity scene and appears in the Build Settings. Disable the SceneBootstrapper in the GameSystems menu if you want to explore those individual scenes.

Many projects also include a staging area for the main menu after the bootstrap scene. This demo project omits a main menu scene.

Other features

C# Style Guide

The StyleExample.cs file in _StyleGuide folder is a project-specific style guide for C# naming conventions, formatting rules, and usage guidelines, most of which are applied in QuizU. This promotes readability and consistency in coding, especially when working in a team environment.

While there is no “right style” other than what works best for you and your team, the style we are following here is inspired by general industry standards for C#. In our demo we decided to make a few tweaks from the original guide as an example. While following general standards is recommended, the key is not to follow standards for the sake of standards but to ultimately agree on a consistent code style for a project that enables your team to develop a clean, readable, and scalable codebase.

You can learn more by checking out our e-book Create a C# code style guide (Unity 6 edition) for more information about style guides.

Utilities

The project includes some helpful smaller scripts not specific to the quiz application which can be found in the \Quiz\Scripts\Utilities folder. It’s a good idea to start by exploring these first to understand how the project is structured:

  • EventRegistry: This utility class manages the registration and unregistration of UI Toolkit events. Because so much of the game flow hinges on setting up events, the EventRegistry makes that process easier. See Event handling in UI Toolkit for more information.
  • Coroutines: This helper class provides static methods for managing coroutines. This can help a System.Object or ScriptableObject run a coroutine on a separate MonoBehaviour.
  • DestroyOnLoad: Apply this to temporary objects to remove them during the scene load process.
  • NullRefChecker: If you are using the Inspector to set required dependencies, use this to validate your fields. Bypass this behavior using the custom Optional attribute.
  • Tooltip: This shows how to use a UI Toolkit Manipulator to make a simple tooltip that stays within the boundaries of the screen.

ScriptTemplates

The ScriptTemplates folder includes two files to set up formatting, namespaces, and base classes for new MonoBehaviours and ScriptableObjects. Similar to the utilities, they are not specific to the demo and you can modify or create additional templates as needed.

ScriptableObjects

Finally, we use ScriptableObjects as data containers to help us manage information such as questions, quizzes, and menu data. Using ScriptableObjects, we can easily separate data from logic which simplifies data management for more streamlined development.

For more about ScriptableObjects, see the e-book Create modular game architecture with ScriptableObjects from our best practices guides.

So, that’s our first post in our series that unpacks the new QuizU demo. Feel free to leave your comments and questions for each post in this series. The team and I look forward to hearing from you. Thanks for reading!

21 Likes

I really loved the project! This is really efficient and flexible project.
The more I read the post, the more I understand how useful the project is.

  • “IState” structure is so much good idea.
  • StyleExample.cs file is also good for developers!
    And other stuff.

I found a bug in the project and fixed like this:
Issue : When try to click “back” button in the “DemoSelection” scene the button is not work.
Solution: change value of “k_ScenePathToUnload” field in the “DemoSelectionSetup.cs” script.
From : “Assets/Demos/0_DemoSelection/DemoSelection.unity”;
To : “Assets/Unity Technologies/QuizU - A UI Toolkit demo/Demos/0_DemoSelection/DemoSelection.unity”;

1 Like

Glad to hear the project has been helpful Mj-Kkaya. Really appreciate it! Good catch on the bug. We will get that fixed in the next update of it. Question - anything you feel the project was missing we should add in future updates?

If so, I’d be happy to share it.
But first I need to read all the articles about the project and then answer this question.
Thanks a lot.

1 Like

Hi @thomas_jacobsen_unity and @TechnicalContentTeam,

I guess I have found a issue or am I wrong?

The problem is “Actions”" of “UIEvents” doesn’t assigned in the “EventLink” object.
Because delegates are “immutable”?

Because of this issue; the “OnEventRaised” of “EventLink” never trigger and EventLink’s “validation” is never return “true”.
And CurrentState is never changes in the StateMachine => Loop method, because of this line “if (CurrentState.ValidateLinks(out var nextState))”. This line always return “false”.

This behavior doesn’t affect UI scenes transition. But the CurrentState is never changes.

I made some changes at EventLink class and it works but this is not stable solution.

 public EventLink(ref Action gameEvent, IState nextState)
        {
            gameEvent += OnEventRaised;
            m_NextState = nextState;
            Debug.Log($"EventLink-m_GameEvent:{m_GameEvent}, nextState{((AbstractState)m_NextState).Name}!");
        }

This change ensures that the system works correctly, but the assignment at “gameEvent” must be removed in “Disable()”.

Unity version : 2022.3.11f1

Best regards.

Hi Mj-Kkaya,

There is a fix for this broken state pattern that is unreleased. Yes, if you use ref, the state changes correctly but you won’t be able to unregister the OnEventRaised in Disable. I think the solution was either to wrap the event inside of an object or pass the subscribe/unsubscribe actions from the SequenceManager (which works but has verbose syntax).

None of the EventLinks are actually used for the gameplay. This was a holdover from an early version of the project. Originally we wanted GameObjects to react to the state changes.

We’ll make sure this is working properly in the next update since the state pattern can help your UI communicate with the overall game flow.

1 Like

I really like this project and want to understand the architecture and how to reuse it.
Using Unity 2023.3, UI Toolkit, I am looking at the QuizU sample project in order to use the relevant parts in a game (escape RPG) I am developing as part of a research project looking at ‘games with a purpose’ other than entertainment.

My current game has ten scenes joined by a variety of triggers and a ‘shaky’ menu system, as well as a couple of quiz elements built into the scenes for the player to do a situation assessment and make decisions.
The QuizU sample contains much more robust, decoupled architecture as well as a quiz element which I could adapt, so I intend reuse elements in my project.
However, my programming skills are ‘under development’ and I am trying to get up to speed with the how the architecture is implemented at the code level.

My question is… what is the best approach / suggested workflow for integration of exisiting scenes into the QuizU project or vice-versa (QuizU into my project).
Regarding the educational component of these projects (Runner Template, Dragon Crushers) I appreciate that you are trying to address an audience of significantly varying levels of technical experience, but I have found these to be cool ‘show cases’ of Unity’s capabilities, but are overwhelming for beginner level programmers.
I would suggest the show case version of the project, but also a the simplest grey prototype, using primitive shapes, outlining the concepts in a way which is probably embarassingly simple for your development team, but extremely useful for beginner level developers.

2 Likes

Hello

This is my 1st time attempting to open the QuizU project in unity 2022.3.14 but Im having issues:

  1. When I press play in the editor I see “Enter play to Start”, but when I hover the mouse there, a blue rectangle appears on top of everything and nothing happens if I click on anything

  2. When I check the game objects (SequenceManager, BootloadScreen, etc) in the scene, in the inspector all scripts appear as missing, so I cannot see what game object is using what script

  3. When I open any .cs file, it opens individually in a separate VS 2019 window, so I tried opening the c# project (from Assets → Open C# Project) but this error appears (its like the VS solution is broken):

Can you please help me with such issues? maybe Im missing something extra that has to be done after opening the QuizU project? It looks really interesting to learn UI Toolkit but these issues are a blocker for me to follow through the scene and code, I mean at least if I was able to see the missing scripts from the inspector in all game objects would be nice

Does UI Toolkit work for World view canvases yet?

Yes, checkout the 6.2 beta which just launched to test the new “World Space UI for UI Toolkit”:

When I try to install QuizU on a fresh project version 6000.1.6f1, I get a bunch of errors for missing namespace Localized String.

Assets\Unity Technologies\QuizU - A UI Toolkit demo\Demos\13_Localization\SmartStringDemo.cs(22,26): error CS0246: The type or namespace name 'Localization' could not be found (are you missing a using directive or an assembly reference?)

1 Like

I ran into the same issue. Open Window › Package Manager, switch to Unity Registry, and install the Localization package - doing so clears those errors.

3 Likes

Thank you this worked! It seems like they forgot to include this package by default.

Thanks kavanavak. Yes the updated version is using the localization package. We recently launched a two part tutorial on how to use the package so feel free to check that out if you want to learn more it: https://www.youtube.com/watch?v=TTimh8e3qVg

1 Like

So adding the Localization package let us use the project, however when trying to open the corresponding uxml :

And then a bunch of console prints

Advanced text system cannot render using static font asset Roboto
UnityEngine.UIElements.ATGTextJobSystem/PrepareShapingJob:Execute (int)
Unity.Jobs.IJobForExtensions/ForJobStruct`1<UnityEngine.UIElements.ATGTextJobSystem/PrepareShapingJob>:Execute (UnityEngine.UIElements.ATGTextJobSystem/PrepareShapingJob&,intptr,intptr,Unity.Jobs.LowLevel.Unsafe.JobRanges&,int)

So it seems Roboto font related ?

Also only the bottom half get updated (I guess the UXML based binding is broken because of the affordmentionned issue)