We are going to build a ListView that displays the number of GameObjects with a "LocalGame" tag and the names of the corresponding GameObjects. When we click on the item in the list view we will be taken to the JoinGameScreen.
Just to be upfront, the approach we take to build this ListView is overkill for the number of GameObjects we will be counting. ListViews are good when all you want to do is bind data to visible items currently in the view and there are hundreds of items. As we scroll through the list, data will bind and appear and then unbind as we scroll past it. Again, this is overkill for just a few items, but we at Moetsi personally could not find any other resources published online explaining how to do this from scratch, so that just leaves us to do it!!!
We will create a new uxml file named "ListItem" that we will add and remove in the ListView. This is called "Instancing UI Documents as Templates" by Unity in their documentation. Next, we will make a ne w script named "LocalGamesFinder" that will power this new ListView. The reason it is called LocalGamesFinder is because we will be using it to find LAN games in the next Multiplayer section.
There are 3 spells you must cast to conjure ListView:
itemsSource (declares the data source of the items)
makeItem (creates the list item visual element from our uxml)
bindItem (attach the data from our itemsSource to our item)
When you update the data in itemsSource you can call Refresh() to update the list.
We do this differently in the next Multiplayer section, where we'll be listening for game broadcasts, and as new ones are found, we update our list.
In this page we will look for GameObjects in our scene and refresh our itemsSource 1x per second. This is not an optimal approach because it refreshes even when no items have changed, but it is fine to simply demonstrate the purposes of ListView.
Building our ListView
Creating ListItem uxml
Since we've already explained how to create and style uxmls using UI Builder on the previous page ("Styling a View"), we're going to just jump straight to the code here.
Create a new uxml file named ListItem (right-click in the UI folder, select Create, then UI Toolkit, and select UI Document)
We will be taking the names of found GameObjects with "LocalGame" tags and inserting them in the label #game-name from the uxml
When we click on #join-local-game we will be taken to the local games view
Creating LocalGamesFinder
In NavigationScene, create an empty GameObject in the Hierarchy named "LocalGamesDiscovery"
Add component to LocalGamesDiscovery that is a new script named "LocalGamesFinder"
First make the file by right-clicking in the Scripts and Prefabs folder > Create > C# Script and name the file "LocalGamesFinder"
Then Navigate to LocalGamesDiscovery in Hierarchy and click Add Component in Inspector to add LocalGamesFinder
Paste the code snippet below into LocalGamesFinder.cs:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
using UnityEditor;
public class LocalGamesFinder : MonoBehaviour
{
//We will be pulling in our SourceAsset from TitleScreenUI GameObject so we can reference Visual Elements
public UIDocument m_TitleUIDocument;
//When we grab the rootVisualElement of our UIDocument we will be able to query the TitleScreenManager Visual Element
private VisualElement m_titleScreenManagerVE;
//We will query for our TitleScreenManager cVE by its name "TitleScreenManager"
private TitleScreenManager m_titleScreenManagerClass;
//Within TitleScreenManager (which is everything) we will query for our list-view by name
//We don't have to query for the TitleScreen THEN list-view because it is one big tree of elements
//We can call any child from the parent, very convenient! But you must be mindful about being dilligent about
//creating unique names or else you can get back several elements (which at times is the point of sharing a name)
private ListView m_ListView;
//Although this variable name doesn't make sense for this use case it will in the Multiplayer section
//Here we will store our discovered GameObjects
//This will be used as our itemSource
private GameObject[] discoveredServerInfoObjects;
//This is our ListItem uxml that we will drag to the public field
//We need a reference to the uxml so we can build it in makeItem
public VisualTreeAsset m_localGameListItemAsset;
//These variables are used in Update() to pace how often we check for GameObjects
public float perSecond = 1.0f;
private float nextTime = 0;
void OnEnable()
{
//Here we grab the SourceAsset rootVisualElement
//This is a MAJOR KEY, really couldn't find this key step in information online
//If you want to reference your active UI in a script make a public UIDocument variable and
//then call rootVisualElement on it, from there you can query the Visual Element tree by names
//or element types
m_titleScreenManagerVE = m_TitleUIDocument.rootVisualElement;
//Here we grab the TitleScreenManager by querying by name
m_titleScreenManagerClass = m_titleScreenManagerVE.Q<TitleScreenManager>("TitleScreenManager");
//From within TitleScreenManager we query local-games-list by name
m_ListView = m_titleScreenManagerVE.Q<ListView>("local-games-list");
}
// Start is called before the first frame update
void Start()
{
//We start by looking for any GameObjects with a LocalGame tag
discoveredServerInfoObjects = GameObject.FindGameObjectsWithTag("LocalGame");
// The three spells you must cast to conjure a list view
m_ListView.makeItem = MakeItem;
m_ListView.bindItem = BindItem;
m_ListView.itemsSource = discoveredServerInfoObjects;
}
private VisualElement MakeItem()
{
//Here we take the uxml and make a VisualElement
VisualElement listItem = m_localGameListItemAsset.CloneTree();
return listItem;
}
private void BindItem(VisualElement e, int index)
{
//We add the game name to the label of the list item
e.Q<Label>("game-name").text = discoveredServerInfoObjects[index].name;
//Here we create a call back for clicking on the list item and provide data to a function
e.Q<Button>("join-local-game").RegisterCallback<ClickEvent>(ev => ClickedJoinGame(discoveredServerInfoObjects[index]));
}
void ClickedJoinGame(GameObject localGame)
{
//We query our JoinGameScreen cVE and call a new function LoadJoinScreenForSelectedServer and pass our GameObject
//This is an example of clicking a list item and passing through data to a new function with that click
//You will see in our JoinGameScreen cVE that we use this data to fill labels in the view
m_titleScreenManagerClass.Q<JoinGameScreen>("JoinGameScreen").LoadJoinScreenForSelectedServer(localGame);
//We then call EnableJoinScreen on our TitleScreenManager cVE (which displays JoinGameScreen)
m_titleScreenManagerClass.EnableJoinScreen();
}
// Update is called once per frame
void Update()
{
if (Time.time >= nextTime)
{
//We check for GameObjects with a localGame tag
discoveredServerInfoObjects = GameObject.FindGameObjectsWithTag("LocalGame");
//We again set our itemsSource to our array (if the array changes it must be reset)
m_ListView.itemsSource = discoveredServerInfoObjects;
//We then must refresh the listView on this new data source
//(don't worry it doesn't make the list jump, ListView is cool like that)
m_ListView.Refresh();
//We increment
nextTime += (1/perSecond);
}
}
}
Let's also update our JoinGameScreen custom Visual Element (cVE) with the function that our ListItem button (join-local-game) calls, "LoadJoinScreenForSelectedServer"
To update, paste the code snippet below into JoinGameScreen.cs (cVE):
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Net.NetworkInformation;
using System.Collections;
using System.Threading.Tasks;
using System.Threading;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
using Unity.Entities;
using Unity.NetCode;
using UnityEngine.SceneManagement;
public class JoinGameScreen : VisualElement
{
Label m_GameName;
Label m_GameIp;
TextField m_PlayerName;
String m_HostName = "";
IPAddress m_MyIp;
public new class UxmlFactory : UxmlFactory<JoinGameScreen, UxmlTraits> { }
public JoinGameScreen()
{
this.RegisterCallback<GeometryChangedEvent>(OnGeometryChange);
}
void OnGeometryChange(GeometryChangedEvent evt)
{
//
// PROVIDE ACCESS TO THE FORM ELEMENTS THROUGH VARIABLES
//
m_GameName = this.Q<Label>("game-name");
m_GameIp = this.Q<Label>("game-ip");
m_PlayerName = this.Q<TextField>("player-name");
// CLICKING CALLBACKS
this.Q("launch-join-game")?.RegisterCallback<ClickEvent>(ev => ClickedJoinGame());
this.UnregisterCallback<GeometryChangedEvent>(OnGeometryChange);
}
void ClickedJoinGame()
{
Debug.Log("clicked join game");
}
public void LoadJoinScreenForSelectedServer(GameObject localGame)
{
m_GameName = this.Q<Label>("game-name");
m_GameIp = this.Q<Label>("game-ip");
m_GameName.text = localGame.name;
m_GameIp.text = localGame.name;
}
}
🔑MAJOR KEY ALERT🔑
The next few steps we take with LocalGamesFinder will show you a good approach for making scripts that interact with active UI. The general steps to follow are:
Make a public UI Document variable in your script
Drag your UI SourceAsset into that field in the Inspector from the scene's Hierarchy
Call .rootVisualElement on that variable
You can now query your entire Visual Element tree
Select LocalGamesDiscovery so LocalGamesFinder is visible in the Inspector
Drag the TitleScreenUI GameObject from the Hierarchy onto the "Title UI Document" field under Local Games Finder in Inspector
Drag ListItem from the Assets/UI folder in the Project folder to the "Local Game List Item Asset" field
In LoadJoinScreenForSelectedServer in JoinGameScreen cVE
We query for "game-name" and "game-ip" labels
We then set the text value of those labels to the name of our GameObjects
Delete the Debug.Log in "EnableJoinScreen()" in TitleScreenManager cVE
Now let's create an empty GameObject called LocalGame
Add a "LocalGame" tag to the LocalGame GameObject
To do this, you need to click the dropdown next to "Tag" in the Inspector when LocalGame is selected and choose the last option "Add Tag..." and click the + under Tags and type "LocalGame" to make a new tag
Copy and paste to make 10 copies
Let's hit play
Scroll up and down the list to see all our "LocalGames"
Copy and paste and make more GameObjects and see the ListView include those items
Click on Join button on one of the ListItems and check out the JoinGameScreen
Return back and click on another ListItem to see new data load
Place the LocalGamesFinder script in Assets/Scripts and Prefabs/Multiplayer Setup
No gif here, we believe in you 💪
We now have our working ListView that dynamically updates and can pass data when an item is clicked
We created ListItem uxml and added its classes to TitleScreenUI USS
We created LocalGamesDiscovery
We created LocalGamesFinder
We pulled in the UI GameObject in the scene to a public LocalGamesFinder field to be able to access the UI from a MonoBehaviour (major key!)
We updated JoinGameScreen cVE
We updated TitleScreenManager cVE (barely)
We created a new tag and GameObjects to replicate finding new local games