This commit is contained in:
Даниил Заикин
2026-06-17 20:44:53 +03:00
parent 9d153773c2
commit b133e7c656
1880 changed files with 244545 additions and 0 deletions
@@ -0,0 +1,32 @@
{
"name": "Blocks.Sessions",
"rootNamespace": "Blocks.Sessions",
"references": [
"GUID:fe25561d224ed4743af4c60938a59d0b",
"GUID:37e17ffe38d86ae48bc3207e83ffef88",
"GUID:510d22f9fb515c2299f915419086bb2b",
"GUID:97271b4cf421601668d136f3ed0c346d"
],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [
"MULTIPLAYER_SERVICES_1_2_0_OR_NEWER"
],
"versionDefines": [
{
"name": "com.unity.netcode.gameobjects",
"expression": "2.0.0",
"define": "GAMEOBJECTS_NETCODE_2_AVAILABLE"
},
{
"name": "com.unity.services.multiplayer",
"expression": "1.2.0",
"define": "MULTIPLAYER_SERVICES_1_2_0_OR_NEWER"
}
],
"noEngineReferences": false
}
@@ -0,0 +1,14 @@
fileFormatVersion: 2
guid: 04cd0fcb7df77978d80694eb9068d427
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 341930
packageName: Unity Building Block - Multiplayer Session
packageVersion: 1.0
assetPath: Assets/Blocks/MultiplayerSession/Runtime/Blocks.Sessions.asmdef
uploadId: 814574
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: c698a854f3045624996a22147edfcc69
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,124 @@
using System.Collections.Generic;
using Blocks.Common;
using Blocks.Sessions.Common;
using Unity.Properties;
using UnityEngine;
using UnityEngine.UIElements;
namespace Blocks.Sessions
{
[UxmlElement]
public partial class CreateSessionElement : VisualElement
{
const string k_EnterSessionNamePlaceholder = "Enter Session Name";
const string k_CreateButtonText = "CREATE";
[CreateProperty, UxmlAttribute]
public SessionSettings SessionSettings
{
get => m_SessionSettings;
set
{
if (m_SessionSettings == value)
return;
m_SessionSettings = value;
if (panel != null)
UpdateBindings();
}
}
SessionSettings m_SessionSettings;
CreateSessionViewModel m_ViewModel;
readonly List<DataBinding> m_Bindings = new();
public CreateSessionElement()
{
AddToClassList(BlocksTheme.ContainerHorizontal);
var enabledBinding = new DataBinding
{
dataSourcePath = new PropertyPath(nameof(m_ViewModel.CanRegisterSession)),
bindingMode = BindingMode.ToTarget
};
SetBinding(new BindingId(nameof(enabledSelf)), enabledBinding);
m_Bindings.Add(enabledBinding);
var sessionNameTextField = new TextField
{
textEdition =
{
placeholder = k_EnterSessionNamePlaceholder,
hidePlaceholderOnFocus = true
}
};
sessionNameTextField.AddToClassList(BlocksTheme.TextField);
sessionNameTextField.AddToClassList(BlocksTheme.SpaceRight);
var sessionNameBinding = new DataBinding
{
dataSourcePath = new PropertyPath(nameof(m_ViewModel.SessionName)),
bindingMode = BindingMode.ToSource
};
sessionNameTextField.SetBinding("value", sessionNameBinding);
Add(sessionNameTextField);
m_Bindings.Add(sessionNameBinding);
var createSessionButton = new Button
{
text = k_CreateButtonText
};
createSessionButton.AddToClassList(BlocksTheme.Button);
var createSessionBinding = new DataBinding
{
dataSourcePath = new PropertyPath(nameof(m_ViewModel.HasSessionName)),
bindingMode = BindingMode.ToTarget
};
createSessionButton.SetBinding(new BindingId(nameof(enabledSelf)), createSessionBinding);
createSessionButton.clicked += CreateSession;
Add(createSessionButton);
m_Bindings.Add(createSessionBinding);
RegisterCallback<AttachToPanelEvent>(_ => UpdateBindings());
RegisterCallback<DetachFromPanelEvent>(_ => CleanupBindings());
}
void CreateSession()
{
if (!SessionSettings)
{
Debug.LogError("SessionSettings is null, it needs to be assigned in the uxml.");
return;
}
if (!m_ViewModel.AreMultiplayerServicesInitialized())
{
Debug.LogError("Multiplayer Services are not initialized. You can initialize them with default settings by adding a ServicesInitialization and PlayerAuthentication components in your scene.");
return;
}
_ = m_ViewModel.CreateSessionAsync(SessionSettings.ToSessionOptions());
}
void UpdateBindings()
{
CleanupBindings();
m_ViewModel = new CreateSessionViewModel(SessionSettings?.sessionType);
foreach (var binding in m_Bindings)
{
binding.dataSource = m_ViewModel;
}
}
void CleanupBindings()
{
m_ViewModel?.Dispose();
m_ViewModel = null;
foreach (var binding in m_Bindings)
{
binding.dataSource = null;
}
}
}
}
@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 975cfeeaa0b804d48ae43d4abf031ebf
AssetOrigin:
serializedVersion: 1
productId: 341930
packageName: Unity Building Block - Multiplayer Session
packageVersion: 1.0
assetPath: Assets/Blocks/MultiplayerSession/Runtime/CreateSession/CreateSessionElement.cs
uploadId: 814574
@@ -0,0 +1,140 @@
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Unity.Properties;
using Unity.Services.Multiplayer;
using UnityEngine.UIElements;
namespace Blocks.Sessions
{
public class CreateSessionViewModel : IDisposable, IDataSourceViewHashProvider, INotifyBindablePropertyChanged
{
SessionObserver m_SessionObserver;
ISession m_Session;
long m_UpdateVersion;
[CreateProperty]
public bool CanRegisterSession
{
get => m_CanRegisterSession;
private set
{
if (m_CanRegisterSession == value)
return;
m_CanRegisterSession = value;
++m_UpdateVersion;
Notify();
}
}
bool m_CanRegisterSession = true;
[CreateProperty]
public bool HasSessionName
{
get => m_HasSessionName;
private set
{
if (m_HasSessionName == value)
return;
m_HasSessionName = value;
Notify();
}
}
bool m_HasSessionName;
[CreateProperty]
public string SessionName
{
get => m_SessionName;
private set
{
if (m_SessionName == value)
return;
m_SessionName = value;
HasSessionName = m_SessionName != "";
++m_UpdateVersion;
Notify();
}
}
string m_SessionName;
public CreateSessionViewModel(string sessionType)
{
m_SessionObserver = new SessionObserver(sessionType);
m_SessionObserver.AddingSessionStarted += OnAddingSessionStarted;
m_SessionObserver.SessionAdded += OnSessionAdded;
m_SessionObserver.AddingSessionFailed += OnAddingSessionFailed;
if (m_SessionObserver.Session != null)
{
OnSessionAdded(m_SessionObserver.Session);
}
}
void OnAddingSessionFailed(AddingSessionOptions session, SessionException exception) => CanRegisterSession = true;
void OnAddingSessionStarted(AddingSessionOptions session) => CanRegisterSession = false;
void OnSessionAdded(ISession session)
{
m_Session = session;
m_Session.RemovedFromSession += OnSessionRemoved;
m_Session.Deleted += OnSessionRemoved;
CanRegisterSession = false;
}
void OnSessionRemoved()
{
m_Session.RemovedFromSession -= OnSessionRemoved;
m_Session.Deleted -= OnSessionRemoved;
m_Session = null;
CanRegisterSession = true;
}
public bool AreMultiplayerServicesInitialized()
{
return MultiplayerService.Instance != null;
}
public async Task<IHostSession> CreateSessionAsync(SessionOptions sessionOptions)
{
sessionOptions.Name = SessionName;
return await MultiplayerService.Instance.CreateSessionAsync(sessionOptions);
}
public void Dispose()
{
if (m_SessionObserver != null)
{
m_SessionObserver.AddingSessionStarted -= OnAddingSessionStarted;
m_SessionObserver.SessionAdded -= OnSessionAdded;
m_SessionObserver.AddingSessionFailed -= OnAddingSessionFailed;
m_SessionObserver.Dispose();
m_SessionObserver = null;
}
if (m_Session != null)
{
m_Session.RemovedFromSession -= OnSessionRemoved;
m_Session.Deleted -= OnSessionRemoved;
m_Session = null;
}
}
/// <summary>
/// This method is used by UIToolkit to determine if any data bound to the UI has changed.
/// Instead of hashing the data, an m_UpdateVersion counter is incremented when changes occur.
/// </summary>
public long GetViewHashCode() => m_UpdateVersion;
/// <summary>
/// Suggested implementation of INotifyBindablePropertyChanged from UIToolkit.
/// </summary>
public event EventHandler<BindablePropertyChangedEventArgs> propertyChanged;
void Notify([CallerMemberName] string property = null) =>
propertyChanged?.Invoke(this, new BindablePropertyChangedEventArgs(property));
}
}
@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 99041548465e15845b967682ac2b66a1
AssetOrigin:
serializedVersion: 1
productId: 341930
packageName: Unity Building Block - Multiplayer Session
packageVersion: 1.0
assetPath: Assets/Blocks/MultiplayerSession/Runtime/CreateSession/CreateSessionViewModel.cs
uploadId: 814574
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: d1a06b25d29635548b3195d8f20e872f
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,115 @@
using System.Collections.Generic;
using Blocks.Common;
using Blocks.Sessions.Common;
using Unity.Properties;
using UnityEngine;
using UnityEngine.UIElements;
namespace Blocks.Sessions
{
[UxmlElement]
public partial class JoinSessionByCode : VisualElement
{
const string k_SessionCodeTextFieldPlaceholder = "Enter Session Code";
const string k_JoinButtonText = "JOIN";
[UxmlAttribute, CreateProperty]
SessionSettings SessionSettings
{
get => m_SessionSettings;
set
{
if (m_SessionSettings == value)
{
return;
}
m_SessionSettings = value;
if (panel != null)
{
UpdateBindings();
}
}
}
SessionSettings m_SessionSettings;
JoinSessionByCodeViewModel m_ViewModel;
readonly List<DataBinding> m_Bindings = new();
public JoinSessionByCode()
{
AddToClassList(BlocksTheme.ContainerHorizontal);
var sessionCodeTextField = new TextField
{
textEdition =
{
placeholder = k_SessionCodeTextFieldPlaceholder,
hidePlaceholderOnFocus = true
}
};
sessionCodeTextField.AddToClassList(BlocksTheme.TextField);
sessionCodeTextField.AddToClassList(BlocksTheme.SpaceRight);
var sessionCodeBinding = new DataBinding
{
dataSourcePath = new PropertyPath(nameof(m_ViewModel.SessionCode)),
bindingMode = BindingMode.ToSource
};
sessionCodeTextField.SetBinding("value", sessionCodeBinding);
Add(sessionCodeTextField);
m_Bindings.Add(sessionCodeBinding);
var createSessionButton = new Button
{
text = k_JoinButtonText
};
createSessionButton.AddToClassList(BlocksTheme.Button);
var createSessionBinding = new DataBinding
{
dataSourcePath = new PropertyPath(nameof(m_ViewModel.CanJoinSession)),
bindingMode = BindingMode.ToTarget
};
createSessionButton.SetBinding(new BindingId(nameof(enabledSelf)), createSessionBinding);
createSessionButton.clicked += JoinSession;
Add(createSessionButton);
m_Bindings.Add(createSessionBinding);
RegisterCallback<AttachToPanelEvent>(_ => UpdateBindings());
RegisterCallback<DetachFromPanelEvent>(_ => CleanupBindings());
}
void JoinSession()
{
if (!m_ViewModel.AreMultiplayerServicesInitialized())
{
Debug.LogError("Multiplayer Services are not initialized. You can initialize them with default settings by adding a Servicesinitialization and PlayerAuthentication components in your scene.");
return;
}
_ = m_ViewModel.JoinSessionByCodeAsync(m_SessionSettings.ToJoinSessionOptions());
}
void UpdateBindings()
{
CleanupBindings();
m_ViewModel = new JoinSessionByCodeViewModel(m_SessionSettings?.sessionType);
foreach (var binding in m_Bindings)
{
binding.dataSource = m_ViewModel;
}
}
void CleanupBindings()
{
m_ViewModel?.Dispose();
m_ViewModel = null;
foreach (var binding in m_Bindings)
{
binding.dataSource = null;
}
}
}
}
@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: fdf5e790676d88e42b60d23a1c94ec3d
AssetOrigin:
serializedVersion: 1
productId: 341930
packageName: Unity Building Block - Multiplayer Session
packageVersion: 1.0
assetPath: Assets/Blocks/MultiplayerSession/Runtime/JoinSessionByCode/JoinSessionByCodeElement.cs
uploadId: 814574
@@ -0,0 +1,136 @@
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Unity.Properties;
using Unity.Services.Multiplayer;
using UnityEngine.UIElements;
namespace Blocks.Sessions
{
public class JoinSessionByCodeViewModel : IDisposable, IDataSourceViewHashProvider, INotifyBindablePropertyChanged
{
const string k_ValidSessionCodeCharacters = "6789BCDFGHJKLMNPQRTWbcdfghjklmnpqrtw";
SessionObserver m_SessionObserver;
ISession m_Session;
long m_UpdateVersion;
[CreateProperty]
public bool CanJoinSession
{
get => m_CanJoinSession;
private set
{
var canJoin = value;
if(canJoin && m_Session != null)
canJoin = false;
if (m_CanJoinSession == canJoin)
return;
m_CanJoinSession = canJoin;
++m_UpdateVersion;
Notify();
}
}
bool m_CanJoinSession;
[CreateProperty]
public string SessionCode
{
get => m_SessionCode;
private set
{
if (m_SessionCode == value)
return;
m_SessionCode = value;
CanJoinSession = CheckIsSessionCodeFormatValid(m_SessionCode);
++m_UpdateVersion;
Notify();
}
}
string m_SessionCode;
public JoinSessionByCodeViewModel(string sessionType)
{
m_SessionObserver = new SessionObserver(sessionType);
m_SessionObserver.SessionAdded += OnSessionAdded;
if (m_SessionObserver.Session != null)
{
OnSessionAdded(m_SessionObserver.Session);
}
}
static bool CheckIsSessionCodeFormatValid(string str)
{
if (string.IsNullOrEmpty(str) || str.Length is < 6 or > 8)
return false;
foreach (var c in str)
{
if (!k_ValidSessionCodeCharacters.Contains(c))
return false;
}
return true;
}
void OnSessionAdded(ISession session)
{
m_Session = session;
m_Session.RemovedFromSession += OnSessionRemoved;
m_Session.Deleted += OnSessionRemoved;
CanJoinSession = false;
}
void OnSessionRemoved()
{
m_Session.RemovedFromSession -= OnSessionRemoved;
m_Session.Deleted -= OnSessionRemoved;
m_Session = null;
CanJoinSession = CheckIsSessionCodeFormatValid(SessionCode);
}
public bool AreMultiplayerServicesInitialized()
{
return MultiplayerService.Instance != null;
}
public async Task<ISession> JoinSessionByCodeAsync(JoinSessionOptions joinSessionOptions)
{
return await MultiplayerService.Instance.JoinSessionByCodeAsync(SessionCode, joinSessionOptions);
}
public void Dispose()
{
if (m_SessionObserver != null)
{
m_SessionObserver.SessionAdded -= OnSessionAdded;
m_SessionObserver.Dispose();
m_SessionObserver = null;
}
if (m_Session != null)
{
m_Session.RemovedFromSession -= OnSessionRemoved;
m_Session.Deleted -= OnSessionRemoved;
m_Session = null;
}
}
/// <summary>
/// This method is used by UIToolkit to determine if any data bound to the UI has changed.
/// Instead of hashing the data, an m_UpdateVersion counter is incremented when changes occur.
/// </summary>
public long GetViewHashCode() => m_UpdateVersion;
/// <summary>
/// Suggested implementation of INotifyBindablePropertyChanged from UIToolkit.
/// </summary>
public event EventHandler<BindablePropertyChangedEventArgs> propertyChanged;
void Notify([CallerMemberName] string property = null) =>
propertyChanged?.Invoke(this, new BindablePropertyChangedEventArgs(property));
}
}
@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 5fdbae86b41f456438497221fc9e2b7a
AssetOrigin:
serializedVersion: 1
productId: 341930
packageName: Unity Building Block - Multiplayer Session
packageVersion: 1.0
assetPath: Assets/Blocks/MultiplayerSession/Runtime/JoinSessionByCode/JoinSessionByCodeViewModel.cs
uploadId: 814574
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: eea82fc88ffa9e0488723568ccc9a5f3
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,92 @@
using System;
using Blocks.Common;
using Blocks.Sessions.Common;
using Unity.Properties;
using UnityEngine;
using UnityEngine.UIElements;
namespace Blocks.Sessions
{
[UxmlElement]
public partial class QuickJoinButton : Button
{
const string k_QuickJoinButtonText = "QUICK JOIN";
[UxmlAttribute, CreateProperty]
public SessionSettings SessionSettings
{
get => m_SessionSettings;
set
{
if (m_SessionSettings == value)
{
return;
}
m_SessionSettings = value;
if (panel != null)
{
UpdateBindings();
}
}
}
SessionSettings m_SessionSettings;
[UxmlAttribute]
public QuickJoinSettings QuickJoinSettings;
DataBinding m_DataBinding;
QuickJoinViewModel m_ViewModel;
public QuickJoinButton()
{
text = k_QuickJoinButtonText;
AddToClassList(BlocksTheme.Button);
m_DataBinding = new DataBinding()
{
dataSourcePath = new PropertyPath(nameof(QuickJoinViewModel.CanClickButton)),
bindingMode = BindingMode.ToTarget
};
SetBinding("enabledSelf", m_DataBinding);
clicked += OnQuickJoinButtonClicked;
RegisterCallback<AttachToPanelEvent>(_ => UpdateBindings());
RegisterCallback<DetachFromPanelEvent>(_ => CleanupBindings());
}
void OnQuickJoinButtonClicked()
{
if (!SessionSettings)
{
Debug.LogError("SessionSettings is null, it needs to be assigned in the uxml.");
return;
}
if (!m_ViewModel.AreMultiplayerServicesInitialized())
{
Debug.LogError("Multiplayer Services are not initialized. You can initialize them with default settings by adding a ServicesInitialization and PlayerAuthentication components in your scene.");
return;
}
_ = m_ViewModel.MatchmakeSessionAsync(QuickJoinSettings.ToQuickJoinOptions(), SessionSettings.ToSessionOptions());
}
void UpdateBindings()
{
CleanupBindings();
m_ViewModel = new QuickJoinViewModel(SessionSettings?.sessionType);
m_DataBinding.dataSource = m_ViewModel;
}
void CleanupBindings()
{
if (m_DataBinding.dataSource is IDisposable disposable)
{
disposable.Dispose();
}
m_ViewModel = null;
m_DataBinding.dataSource = null;
}
}
}
@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: f2fe78a7d34bd1b4d84380b9aeacc6a7
AssetOrigin:
serializedVersion: 1
productId: 341930
packageName: Unity Building Block - Multiplayer Session
packageVersion: 1.0
assetPath: Assets/Blocks/MultiplayerSession/Runtime/QuickJoin/QuickJoinButton.cs
uploadId: 814574
@@ -0,0 +1,24 @@
using Unity.Services.Multiplayer;
using UnityEngine;
namespace Blocks.Sessions
{
[CreateAssetMenu(fileName = nameof(QuickJoinSettings), menuName = "Services/Blocks/Session/" + nameof(QuickJoinSettings))]
public class QuickJoinSettings : ScriptableObject
{
[Header("QuickJoinSettings")]
[Tooltip("The timeout in seconds for the quick join to stop trying to join and either fail or create its own session is createSession is true.")]
public float timeout = 5f;
[Tooltip("If true, the quick join will create a session if it cannot find one to join withing the given timeout time frame.")]
public bool createSession = true;
public QuickJoinOptions ToQuickJoinOptions()
{
return new QuickJoinOptions
{
Timeout = System.TimeSpan.FromSeconds(timeout),
CreateSession = createSession
};
}
}
}
@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: d453e3c39a7322043bc13370b81b57f1
AssetOrigin:
serializedVersion: 1
productId: 341930
packageName: Unity Building Block - Multiplayer Session
packageVersion: 1.0
assetPath: Assets/Blocks/MultiplayerSession/Runtime/QuickJoin/QuickJoinSettings.cs
uploadId: 814574
@@ -0,0 +1,125 @@
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Unity.Properties;
using Unity.Services.Multiplayer;
using UnityEngine.UIElements;
namespace Blocks.Sessions
{
public class QuickJoinViewModel : INotifyBindablePropertyChanged, IDataSourceViewHashProvider, IDisposable
{
SessionObserver m_SessionObserver;
ISession m_Session;
long m_UpdateVersion;
/// <summary>
/// This property is bound to <see cref="QuickJoinButton.enabledSelf"/> so that the button is enabled or disabled
/// based on whether a session can be joined. <br/>
/// It is a property using [CreateProperty] attribute to allow for data binding in UIToolkit
/// and using <see cref="Notify"/> to optimize UIToolkit redraws.
/// </summary>
[CreateProperty]
public bool CanClickButton
{
get => m_CanClickButton;
set
{
if (m_CanClickButton == value)
{
return;
}
m_CanClickButton = value;
++m_UpdateVersion;
Notify();
}
}
bool m_CanClickButton = true;
public QuickJoinViewModel(string sessionType)
{
m_SessionObserver = new SessionObserver(sessionType);
m_SessionObserver.AddingSessionStarted += OnAddingSessionStarted;
m_SessionObserver.SessionAdded += OnSessionAdded;
m_SessionObserver.AddingSessionFailed += OnAddingSessionFailed;
if (m_SessionObserver.Session != null)
{
OnSessionAdded(m_SessionObserver.Session);
}
}
void OnAddingSessionFailed(AddingSessionOptions session, Exception exception)
{
CanClickButton = true;
}
void OnAddingSessionStarted(AddingSessionOptions sessionOptions)
{
CanClickButton = false;
}
void OnSessionAdded(ISession newSession)
{
m_Session = newSession;
m_Session.RemovedFromSession += OnSessionRemoved;
m_Session.Deleted += OnSessionRemoved;
CanClickButton = false;
}
void OnSessionRemoved()
{
CanClickButton = true;
CleanupSession();
}
void CleanupSession()
{
m_Session.RemovedFromSession -= OnSessionRemoved;
m_Session.Deleted -= OnSessionRemoved;
m_Session = null;
}
public bool AreMultiplayerServicesInitialized()
{
return MultiplayerService.Instance != null;
}
public async Task<ISession> MatchmakeSessionAsync(QuickJoinOptions quickJoinOptions, SessionOptions sessionOptions)
{
return await MultiplayerService.Instance.MatchmakeSessionAsync(quickJoinOptions, sessionOptions);
}
public void Dispose()
{
if (m_SessionObserver != null)
{
m_SessionObserver.Dispose();
m_SessionObserver = null;
}
if (m_Session != null)
{
CleanupSession();
}
}
/// <summary>
/// This method is used by UIToolkit to determine if any data bound to the UI has changed.
/// Instead of hashing the data, an m_UpdateVersion counter is incremented when changes occur.
/// </summary>
public long GetViewHashCode() => m_UpdateVersion;
/// <summary>
/// Suggested implementation of INotifyBindablePropertyChanged from UIToolkit.
/// </summary>
public event EventHandler<BindablePropertyChangedEventArgs> propertyChanged;
void Notify([CallerMemberName] string property = null)
{
propertyChanged?.Invoke(this, new BindablePropertyChangedEventArgs(property));
}
}
}
@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 0486ed66e217eda44805ac20119a31f1
AssetOrigin:
serializedVersion: 1
productId: 341930
packageName: Unity Building Block - Multiplayer Session
packageVersion: 1.0
assetPath: Assets/Blocks/MultiplayerSession/Runtime/QuickJoin/QuickJoinViewModel.cs
uploadId: 814574
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: cb625a1d04c0f5a4b824e2b529264309
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,215 @@
using System;
using UnityEngine;
using Blocks.Common;
using Unity.Properties;
using UnityEngine.UIElements;
using Blocks.Sessions.Common;
using Unity.Services.Multiplayer;
using System.Collections.Generic;
namespace Blocks.Sessions
{
[UxmlElement]
public partial class SessionBrowserElement : ListView
{
private const string k_JoinButtonText = "JOIN";
private const string k_RefreshButtonText = "REFRESH LIST";
private const string k_NoSessionFoundText = "No sessions found";
private const string k_SessionNameLabel = "SessionNameLabel";
private const string k_SessionPlayerCountLabel = "SessionPlayerCountLabel";
private int m_MaxSessionsDisplayed = 20;
private SessionSettings m_SessionSettings;
private SessionBrowserViewModel m_ViewModel;
private List<DataBinding> m_DataBindings;
private Button m_RefreshButton;
private Button m_JoinSessionButton;
[CreateProperty, UxmlAttribute]
public SessionSettings SessionSettings
{
get => m_SessionSettings;
set
{
if (m_SessionSettings == value)
return;
m_SessionSettings = value;
if (panel != null)
{
UpdateBindingSources();
}
}
}
[CreateProperty, UxmlAttribute]
public int MaxSessionsDisplayed
{
get => m_MaxSessionsDisplayed;
set => m_MaxSessionsDisplayed = value;
}
public SessionBrowserElement()
{
virtualizationMethod = CollectionVirtualizationMethod.FixedHeight;
fixedItemHeight = 56f;
// required for making each element inheriting an indexed array item for the data source path
// if not set, you need to specify the datasource path manually in the bindItem callback for each item
bindingSourceSelectionMode = BindingSourceSelectionMode.AutoAssign;
AddToClassList(BlocksTheme.ScrollView);
AddToClassList(BlocksTheme.SpaceBottom);
makeNoneElement = MakeNoneElement;
makeItem = MakeDefaultItem;
makeFooter = MakeFooter;
RegisterCallback<AttachToPanelEvent>(OnAttachToPanelEvent);
RegisterCallback<DetachFromPanelEvent>(OnDetachFromPanelEvent);
}
private VisualElement MakeFooter()
{
var buttonsContainer = new VisualElement();
buttonsContainer.AddToClassList(BlocksTheme.ContainerHorizontal);
buttonsContainer.AddToClassList(BlocksTheme.ContainerAlignedRight);
m_JoinSessionButton = new Button { text = k_JoinButtonText };
m_JoinSessionButton.AddToClassList(BlocksTheme.Button);
m_JoinSessionButton.AddToClassList(BlocksTheme.SpaceRight);
buttonsContainer.Add(m_JoinSessionButton);
m_RefreshButton = new Button { text = k_RefreshButtonText };
m_RefreshButton.AddToClassList(BlocksTheme.Button);
buttonsContainer.Add(m_RefreshButton);
return buttonsContainer;
}
private void OnRefreshButtonClicked()
{
ClearSelection();
// fire and forget, so we don't block the UI thread
_ = m_ViewModel?.UpdateSessionListAsync(MaxSessionsDisplayed);
}
private void JoinSession()
{
if (!m_ViewModel.SelectedAndAvailable)
{
Debug.LogError("Selected session is no longer selected.");
return;
}
// fire and forget, so we don't block the UI thread
_ = m_ViewModel.JoinSessionAsync(SessionSettings.ToJoinSessionOptions());
}
private void UpdateBindingSources()
{
CleanupBindings();
m_ViewModel = new SessionBrowserViewModel(SessionSettings?.sessionType);
foreach (var dataBinding in m_DataBindings)
{
dataBinding.dataSource = m_ViewModel;
}
}
private void CleanupBindings()
{
m_ViewModel?.Dispose();
m_ViewModel = null;
foreach (var dataBinding in m_DataBindings)
{
dataBinding.dataSource = null;
}
}
private void OnDetachFromPanelEvent(DetachFromPanelEvent evt)
{
CleanupBindings();
m_RefreshButton.clicked -= OnRefreshButtonClicked;
m_RefreshButton.ClearBinding(nameof(SessionBrowserViewModel.CanRefresh));
m_JoinSessionButton.clicked -= JoinSession;
m_JoinSessionButton.ClearBinding(nameof(enabledSelf));
ClearBindings();
}
private void OnAttachToPanelEvent(AttachToPanelEvent evt)
{
m_DataBindings = new List<DataBinding>();
var listBinding = new DataBinding { dataSourcePath = new PropertyPath(nameof(SessionBrowserViewModel.Sessions)), bindingMode = BindingMode.ToTarget };
SetBinding(new BindingId(nameof(ListView.itemsSource)), listBinding);
m_DataBindings.Add(listBinding);
var selectionBinding = new DataBinding { dataSourcePath = new PropertyPath(nameof(SessionBrowserViewModel.SelectedSessionIndex)), bindingMode = BindingMode.TwoWay };
SetBinding(new BindingId(nameof(ListView.selectedIndex)), selectionBinding);
m_DataBindings.Add(selectionBinding);
var joinSessionBinding = new DataBinding { dataSourcePath = new PropertyPath(nameof(SessionBrowserViewModel.SelectedAndAvailable)), bindingMode = BindingMode.ToTarget };
m_JoinSessionButton.SetBinding(new BindingId(nameof(enabledSelf)), joinSessionBinding);
m_DataBindings.Add(joinSessionBinding);
m_JoinSessionButton.clicked += JoinSession;
var refreshBinding = new DataBinding { dataSourcePath = new PropertyPath(nameof(SessionBrowserViewModel.CanRefresh)), bindingMode = BindingMode.ToTarget };
m_RefreshButton.SetBinding(new BindingId(nameof(enabledSelf)), refreshBinding);
m_DataBindings.Add(refreshBinding);
m_RefreshButton.clicked += OnRefreshButtonClicked;
UpdateBindingSources();
}
private static VisualElement MakeNoneElement()
{
var label = new Label(k_NoSessionFoundText);
label.AddToClassList(BlocksTheme.Label);
label.AddToClassList(BlocksTheme.SpaceLeft);
return label;
}
private static VisualElement MakeDefaultItem()
{
var container = new VisualElement();
container.AddToClassList(BlocksTheme.ContainerHorizontal);
container.AddToClassList(BlocksTheme.ScrollViewElement);
container.AddToClassList(BlocksTheme.ContainerSpaceBetween);
var sessionNameLabel = new Label { name = k_SessionNameLabel };
sessionNameLabel.AddToClassList(BlocksTheme.Label);
sessionNameLabel.AddToClassList(BlocksTheme.SpaceLeft);
container.Add(sessionNameLabel);
var db = new DataBinding
{
dataSourcePath = PropertyPath.FromName(nameof(SessionInfoViewModel.Name)),
bindingMode = BindingMode.ToTarget,
updateTrigger = BindingUpdateTrigger.OnSourceChanged
};
sessionNameLabel.SetBinding(nameof(Label.text), db);
var sessionPlayerCountLabel = new Label { name = k_SessionPlayerCountLabel };
sessionPlayerCountLabel.AddToClassList(BlocksTheme.Label);
sessionPlayerCountLabel.AddToClassList(BlocksTheme.SpaceRight);
container.Add(sessionPlayerCountLabel);
var sessionPlayerCountBinding = new DataBinding { bindingMode = BindingMode.ToTarget };
// register a local converter to display relevant session properties as a formatted string
sessionPlayerCountBinding.sourceToUiConverters
.AddConverter((ref SessionInfoViewModel session) => $"{session.MaxPlayers - session.AvailableSlots}/{session.MaxPlayers} Players");
sessionPlayerCountLabel.SetBinding(nameof(Label.text), sessionPlayerCountBinding);
return container;
}
}
}
@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 203f2c9355eb4514f9062db88d0512e1
AssetOrigin:
serializedVersion: 1
productId: 341930
packageName: Unity Building Block - Multiplayer Session
packageVersion: 1.0
assetPath: Assets/Blocks/MultiplayerSession/Runtime/SessionBrowser/SessionBrowserElement.cs
uploadId: 814574
@@ -0,0 +1,274 @@
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Unity.Properties;
using Unity.Services.Core;
using Unity.Services.Multiplayer;
using UnityEngine;
using UnityEngine.UIElements;
namespace Blocks.Sessions
{
public class SessionBrowserViewModel : INotifyBindablePropertyChanged, IDataSourceViewHashProvider, IDisposable
{
private SessionObserver m_SessionObserver;
private ServiceObserver<IMultiplayerService> m_ServiceObserver;
private long m_UpdateVersion;
private bool m_SelectedAndAvailable;
private bool m_CanRefresh;
private int m_SelectedSessionIndex;
private ISession m_Session;
private List<SessionInfoViewModel> m_Sessions;
[CreateProperty]
public List<SessionInfoViewModel> Sessions
{
get => m_Sessions;
set
{
if (m_Sessions == value)
{
return;
}
m_Sessions = value;
++m_UpdateVersion;
Notify();
}
}
[CreateProperty]
public int SelectedSessionIndex
{
get => m_SelectedSessionIndex;
set
{
if (value >= 0 && value < Sessions.Count)
{
m_SelectedSessionIndex = value;
SelectedAndAvailable = true;
}
else
{
SelectedAndAvailable = false;
}
}
}
public string GetSelectedSessionId()
{
if (SelectedSessionIndex >= 0 && SelectedSessionIndex < Sessions.Count)
{
return Sessions[SelectedSessionIndex].Id;
}
return null;
}
[CreateProperty]
public bool SelectedAndAvailable
{
get => m_SelectedAndAvailable;
set
{
var newValue = value;
if (value && m_Session != null && m_Session.Id == GetSelectedSessionId())
{
newValue = false;
}
if (m_SelectedAndAvailable != newValue)
{
m_SelectedAndAvailable = newValue;
++m_UpdateVersion;
Notify();
}
}
}
[CreateProperty]
public bool CanRefresh
{
get => m_CanRefresh;
set
{
if (m_CanRefresh == value)
{
return;
}
m_CanRefresh = value;
++m_UpdateVersion;
Notify();
}
}
public SessionBrowserViewModel(string sessionType)
{
Sessions = new List<SessionInfoViewModel>();
m_SessionObserver = new SessionObserver(sessionType);
m_SessionObserver.SessionAdded += OnSessionAdded;
if (m_SessionObserver.Session != null)
{
OnSessionAdded(m_SessionObserver.Session);
}
// This can be null while in edit mode and needs to be checked before creating the Observer.
if (UnityServices.Instance != null)
{
m_ServiceObserver = new ServiceObserver<IMultiplayerService>();
if (m_ServiceObserver.Service != null)
{
CanRefresh = true;
}
else
{
CanRefresh = false;
m_ServiceObserver.Initialized += OnServicesInitialized;
}
}
}
public async Task JoinSessionAsync(JoinSessionOptions options)
{
try
{
await MultiplayerService.Instance.JoinSessionByIdAsync(GetSelectedSessionId(), options);
}
catch (Exception exception)
{
Debug.LogException(exception);
}
}
void OnServicesInitialized(IMultiplayerService service)
{
m_ServiceObserver.Initialized -= OnServicesInitialized;
CanRefresh = true;
}
internal async Task UpdateSessionListAsync(int numberOfMaxSessions)
{
// if there is no connection to MultiplayerService, do not try to refresh
if (!CanRefresh)
{
Debug.LogWarning("Cannot refresh session list." +
"Multiplayer Services are not initialized." +
"You can initialize them with default settings by adding a " +
"ServicesInitialization and PlayerAuthentication components in your scene.");
return;
}
try
{
CanRefresh = false;
var queryResult = await MultiplayerService.Instance
.QuerySessionsAsync(new QuerySessionsOptions
{
SortOptions = new List<SortOption>
{
new (SortOrder.Descending,SortField.Name)
}
});
// properly dispose the sessionInfo view models first
foreach (var session in Sessions)
{
session.Dispose();
}
Sessions.Clear();
for (var i = 0; (i < Math.Min(queryResult.Sessions.Count, numberOfMaxSessions)); i++)
{
Sessions.Add(new SessionInfoViewModel(queryResult.Sessions[i]));
}
++m_UpdateVersion;
CanRefresh = true;
// reset selection
SelectedSessionIndex = -1;
}
catch (Exception ex)
{
Debug.LogError($"Failed to update session list: {ex.Message}");
}
}
private void OnSessionAdded(ISession newSession)
{
m_Session = newSession;
m_Session.RemovedFromSession += OnSessionRemoved;
m_Session.Deleted += OnSessionRemoved;
if (m_Session.Id == GetSelectedSessionId())
{
SelectedAndAvailable = false;
}
}
private void OnSessionRemoved()
{
var lastSessionId = m_Session.Id;
CleanupSession();
if (lastSessionId == GetSelectedSessionId())
{
SelectedAndAvailable = true;
}
}
private void CleanupSession()
{
m_Session.RemovedFromSession -= OnSessionRemoved;
m_Session.Deleted -= OnSessionRemoved;
m_Session = null;
}
public async Task<ISession> JoinSessionByIdAsync(JoinSessionOptions joinSessionOptions)
{
return await MultiplayerService.Instance.JoinSessionByIdAsync(GetSelectedSessionId(), joinSessionOptions);
}
public void Dispose()
{
if (m_SessionObserver != null)
{
m_SessionObserver.SessionAdded -= OnSessionAdded;
m_SessionObserver.Dispose();
m_SessionObserver = null;
}
if (m_ServiceObserver != null)
{
m_ServiceObserver.Dispose();
m_ServiceObserver = null;
}
if (m_Session != null)
{
CleanupSession();
}
}
/// <summary>
/// This method is used by UIToolkit to determine if any data bound to the UI has changed.
/// Instead of hashing the data, an m_UpdateVersion counter is incremented when changes occur.
/// </summary>
public long GetViewHashCode() => m_UpdateVersion;
/// <summary>
/// Suggested implementation of INotifyBindablePropertyChanged from UIToolkit.
/// </summary>
public event EventHandler<BindablePropertyChangedEventArgs> propertyChanged;
private void Notify([CallerMemberName] string property = null)
{
propertyChanged?.Invoke(this, new BindablePropertyChangedEventArgs(property));
}
}
}
@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: fbab5cc94e2a7ab4cad1d3a5f9174b61
AssetOrigin:
serializedVersion: 1
productId: 341930
packageName: Unity Building Block - Multiplayer Session
packageVersion: 1.0
assetPath: Assets/Blocks/MultiplayerSession/Runtime/SessionBrowser/SessionBrowserViewModel.cs
uploadId: 814574
@@ -0,0 +1,146 @@
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using Unity.Properties;
using Unity.Services.Multiplayer;
using UnityEngine.UIElements;
namespace Blocks.Sessions
{
/// <summary>
/// Provides a DataBinding compatible representation of a <c>Session</c> associated information.
/// </summary>
public class SessionInfoViewModel : ISessionInfo,
INotifyBindablePropertyChanged, IDataSourceViewHashProvider, IDisposable
{
private const string k_Unavailalble = "N/A";
private ISession _session;
private ISessionInfo _sessionInfo;
private long _updateVersion;
public SessionInfoViewModel(ISessionInfo sessionInfo)
{
_sessionInfo = sessionInfo;
}
public SessionInfoViewModel(ISession session)
{
_session = session;
_session.Changed += OnSessionChanged;
_session.SessionHostChanged += OnSessionHostChanged;
_session.SessionPropertiesChanged += OnSessionPropertiesChanged;
// should we attempt to query the associated info?
}
/// <inheritdoc/>
[CreateProperty]
public string Name
=> _sessionInfo?.Name ?? _session?.Name;
/// <inheritdoc/>
[CreateProperty]
public string Id
=> _sessionInfo?.Id ?? _session?.Id;
/// <inheritdoc/>
[CreateProperty]
public string Upid
=> _sessionInfo?.Upid ?? k_Unavailalble;
/// <inheritdoc/>
[CreateProperty]
public string HostId
=> _sessionInfo?.HostId ?? _session?.Host;
/// <inheritdoc/>
[CreateProperty]
public int AvailableSlots
=> _sessionInfo?.AvailableSlots ?? _session?.AvailableSlots ?? 0;
/// <inheritdoc/>
[CreateProperty]
public int MaxPlayers
=> _sessionInfo?.MaxPlayers ?? _session?.MaxPlayers ?? 0;
/// <inheritdoc/>
[CreateProperty]
public bool IsLocked
=> _sessionInfo?.IsLocked ?? _session?.IsLocked ?? true;
/// <inheritdoc/>
[CreateProperty]
public bool HasPassword
=> _sessionInfo?.HasPassword ?? _session?.HasPassword ?? true;
/// <inheritdoc/>
[CreateProperty]
public DateTime LastUpdated
=> _sessionInfo?.LastUpdated ?? DateTime.UnixEpoch;
/// <inheritdoc/>
[CreateProperty]
public DateTime Created
=> _sessionInfo?.Created ?? DateTime.UnixEpoch;
/// <inheritdoc/>
[CreateProperty]
public IReadOnlyDictionary<string, SessionProperty> Properties
=> _sessionInfo?.Properties ?? _session?.Properties;
private void OnSessionHostChanged(string obj)
{
_updateVersion++;
Notify(nameof(HostId));
}
private void OnSessionPropertiesChanged()
{
_updateVersion++;
Notify(nameof(Properties));
}
private void OnSessionChanged()
{
_updateVersion++;
Notify(nameof(Name));
Notify(nameof(LastUpdated));
Notify(nameof(HasPassword));
Notify(nameof(IsLocked));
Notify(nameof(MaxPlayers));
Notify(nameof(AvailableSlots));
}
public void Dispose()
{
if (_session != null)
{
_session.Changed -= OnSessionChanged;
_session.SessionHostChanged -= OnSessionHostChanged;
_session.SessionPropertiesChanged -= OnSessionPropertiesChanged;
}
_session = null;
_sessionInfo = null;
}
/// <summary>
/// This method is used by UIToolkit to determine if any data bound to the UI has changed.
/// Instead of hashing the data, an m_UpdateVersion counter is incremented when changes occur.
/// </summary>
public long GetViewHashCode() => _updateVersion;
/// <summary>
/// Suggested implementation of INotifyBindablePropertyChanged from UIToolkit.
/// </summary>
public event EventHandler<BindablePropertyChangedEventArgs> propertyChanged;
private void Notify([CallerMemberName] string property = null)
{
propertyChanged?.Invoke(this, new BindablePropertyChangedEventArgs(property));
}
}
}
@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: e83d0589eebc4c059679b6f84b0775af
timeCreated: 1761317686
AssetOrigin:
serializedVersion: 1
productId: 341930
packageName: Unity Building Block - Multiplayer Session
packageVersion: 1.0
assetPath: Assets/Blocks/MultiplayerSession/Runtime/SessionBrowser/SessionInfoViewModel.cs
uploadId: 814574