Commit 4495e681 authored by Abdulrahman Mohammed's avatar Abdulrahman Mohammed

Refactor lobby

parent e60515eb
......@@ -553,6 +553,7 @@ GameObject:
- component: {fileID: 8643326269112809739}
- component: {fileID: 80164591121225352}
- component: {fileID: 5761587338744970414}
- component: {fileID: -1920823489099653188}
m_Layer: 0
m_Name: NPC
m_TagString: Untagged
......@@ -717,7 +718,7 @@ MonoBehaviour:
m_Script: {fileID: 11500000, guid: d5a57f767e5e46a458fc5d3c628d0cbb, type: 3}
m_Name:
m_EditorClassIdentifier: Unity.Netcode.Runtime::Unity.Netcode.NetworkObject
GlobalObjectIdHash: 2566835037
GlobalObjectIdHash: 2996614975
InScenePlacedSourceGlobalObjectIdHash: 0
DeferredDespawnTick: 0
Ownership: 1
......@@ -746,7 +747,6 @@ MonoBehaviour:
_score:
m_InternalValue: 0
isNPC: 1
_id: 0
_NPCsId: 0
--- !u!114 &4343223469952472967
MonoBehaviour:
......@@ -850,6 +850,56 @@ MonoBehaviour:
Synchronize: 1
ParameterType: 9
AnimatorParametersExpanded: 0
--- !u!114 &-1920823489099653188
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 6869359625592689313}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 5d7d6b6aa5a393e40a69d8bb4d05b43e, type: 3}
m_Name:
m_EditorClassIdentifier: Assembly-CSharp::PlayerDetails
ShowTopMostFoldoutHeaderGroup: 1
PlayerName:
m_InternalValue:
utf8LengthInBytes: 4
bytes:
offset0000:
byte0000: 78
byte0001: 117
byte0002: 108
byte0003: 108
byte0004: 0
byte0005: 0
byte0006: 0
byte0007: 0
byte0008: 0
byte0009: 0
byte0010: 0
byte0011: 0
byte0012: 0
byte0013: 0
byte0014: 0
byte0015: 0
byte0016: 0
byte0017: 0
byte0018: 0
byte0019: 0
byte0020: 0
byte0021: 0
byte0022: 0
byte0023: 0
byte0024: 0
byte0025: 0
byte0026: 0
byte0027: 0
byte0028: 0
byte0029: 0
nameText: {fileID: 7462257593087947900}
avatar:
--- !u!1001 &97846783079897831
PrefabInstance:
m_ObjectHideFlags: 0
......
......@@ -2160,6 +2160,7 @@ MonoBehaviour:
ShowTopMostFoldoutHeaderGroup: 1
leaderboardParent: {fileID: 914376416}
leaderboardPrefab: {fileID: 3710372465793025137, guid: f37cdc862a6ad5640b311651b5352c81, type: 3}
approvRequest: {fileID: 0}
--- !u!114 &803451463
MonoBehaviour:
m_ObjectHideFlags: 0
......@@ -2185,84 +2186,6 @@ MonoBehaviour:
AutoObjectParentSync: 1
SyncOwnerTransformWhenParented: 1
AllowOwnerToParent: 0
--- !u!1001 &808220198
PrefabInstance:
m_ObjectHideFlags: 0
serializedVersion: 2
m_Modification:
serializedVersion: 3
m_TransformParent: {fileID: 1120066095}
m_Modifications:
- target: {fileID: 5928671268030453073, guid: 29c311971269db94990ae48b1f666293, type: 3}
propertyPath: m_LocalPosition.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 5928671268030453073, guid: 29c311971269db94990ae48b1f666293, type: 3}
propertyPath: m_LocalPosition.y
value: 0.98
objectReference: {fileID: 0}
- target: {fileID: 5928671268030453073, guid: 29c311971269db94990ae48b1f666293, type: 3}
propertyPath: m_LocalPosition.z
value: 7.34
objectReference: {fileID: 0}
- target: {fileID: 5928671268030453073, guid: 29c311971269db94990ae48b1f666293, type: 3}
propertyPath: m_LocalRotation.w
value: 0.9815522
objectReference: {fileID: 0}
- target: {fileID: 5928671268030453073, guid: 29c311971269db94990ae48b1f666293, type: 3}
propertyPath: m_LocalRotation.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 5928671268030453073, guid: 29c311971269db94990ae48b1f666293, type: 3}
propertyPath: m_LocalRotation.y
value: -0.19119437
objectReference: {fileID: 0}
- target: {fileID: 5928671268030453073, guid: 29c311971269db94990ae48b1f666293, type: 3}
propertyPath: m_LocalRotation.z
value: 0
objectReference: {fileID: 0}
- target: {fileID: 5928671268030453073, guid: 29c311971269db94990ae48b1f666293, type: 3}
propertyPath: m_LocalEulerAnglesHint.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 5928671268030453073, guid: 29c311971269db94990ae48b1f666293, type: 3}
propertyPath: m_LocalEulerAnglesHint.y
value: -22.045
objectReference: {fileID: 0}
- target: {fileID: 5928671268030453073, guid: 29c311971269db94990ae48b1f666293, type: 3}
propertyPath: m_LocalEulerAnglesHint.z
value: 0
objectReference: {fileID: 0}
- target: {fileID: 6533416622245416413, guid: 29c311971269db94990ae48b1f666293, type: 3}
propertyPath: GlobalObjectIdHash
value: 4199980813
objectReference: {fileID: 0}
- target: {fileID: 6533416622245416413, guid: 29c311971269db94990ae48b1f666293, type: 3}
propertyPath: SceneMigrationSynchronization
value: 0
objectReference: {fileID: 0}
- target: {fileID: 6533416622245416413, guid: 29c311971269db94990ae48b1f666293, type: 3}
propertyPath: InScenePlacedSourceGlobalObjectIdHash
value: 2996614975
objectReference: {fileID: 0}
- target: {fileID: 6869359625592689313, guid: 29c311971269db94990ae48b1f666293, type: 3}
propertyPath: m_Name
value: NPC
objectReference: {fileID: 0}
- target: {fileID: 6869359625592689313, guid: 29c311971269db94990ae48b1f666293, type: 3}
propertyPath: m_IsActive
value: 1
objectReference: {fileID: 0}
m_RemovedComponents: []
m_RemovedGameObjects: []
m_AddedGameObjects: []
m_AddedComponents: []
m_SourcePrefab: {fileID: 100100000, guid: 29c311971269db94990ae48b1f666293, type: 3}
--- !u!4 &808220199 stripped
Transform:
m_CorrespondingSourceObject: {fileID: 5928671268030453073, guid: 29c311971269db94990ae48b1f666293, type: 3}
m_PrefabInstance: {fileID: 808220198}
m_PrefabAsset: {fileID: 0}
--- !u!1 &825301023
GameObject:
m_ObjectHideFlags: 0
......@@ -2376,7 +2299,9 @@ MonoBehaviour:
maxPlayer: 0
gameManagerScript: {fileID: 764357412}
fadeScript: {fileID: 1270500663}
approvRequest: {fileID: 0}
playerPrefab: {fileID: -5192139548446471021, guid: 5922d3cf9c6f4784f8277e3d39518356, type: 3}
npcPrefab: {fileID: 6533416622245416413, guid: 29c311971269db94990ae48b1f666293, type: 3}
npcParent: {fileID: 1120066095}
--- !u!114 &911744692
MonoBehaviour:
m_ObjectHideFlags: 0
......@@ -2966,6 +2891,7 @@ GameObject:
serializedVersion: 6
m_Component:
- component: {fileID: 1120066095}
- component: {fileID: 1120066096}
m_Layer: 0
m_Name: NPCs
m_TagString: Untagged
......@@ -2985,10 +2911,34 @@ Transform:
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children:
- {fileID: 808220199}
m_Children: []
m_Father: {fileID: 1891997311}
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!114 &1120066096
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1120066094}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: d5a57f767e5e46a458fc5d3c628d0cbb, type: 3}
m_Name:
m_EditorClassIdentifier: Unity.Netcode.Runtime::Unity.Netcode.NetworkObject
GlobalObjectIdHash: 3619114659
InScenePlacedSourceGlobalObjectIdHash: 0
DeferredDespawnTick: 0
Ownership: 1
AlwaysReplicateAsRoot: 0
SynchronizeTransform: 1
ActiveSceneSynchronization: 0
SceneMigrationSynchronization: 0
SpawnWithObservers: 1
DontDestroyWithOwner: 0
AutoObjectParentSync: 1
SyncOwnerTransformWhenParented: 1
AllowOwnerToParent: 0
--- !u!1001 &1125776865
PrefabInstance:
m_ObjectHideFlags: 0
......
This diff is collapsed.
fileFormatVersion: 2
guid: 352bf19a87eb5f84da505d6b76a39310
guid: 3e56ca6796df8164c946c1e398109b90
DefaultImporter:
externalObjects: {}
userData:
......
This diff is collapsed.
This diff is collapsed.
using Unity.Services.Authentication;
using TMPro;
using Unity.Services.Core;
using UnityEngine;
using UnityEngine.UI;
public class AppInit : MonoBehaviour
{
[SerializeField] TMP_InputField playerName;
[SerializeField] Button joinButton;
private async void Start()
{
Application.targetFrameRate = 60;
await UnityServices.InitializeAsync();
joinButton.onClick.AddListener(Join);
}
private async void Join()
{
FadeWithText.Instance.ShowMessage("جاري التحميل...", false);
await AuthenticationRequest.StartAuth();
FadeWithText.Instance.FadeOut();
string name;
if (!string.IsNullOrEmpty(playerName.text))
{
name = playerName.text;
}
else
name = "Player#" + Random.Range(1000, 9999);
PlayerPrefs.SetString("PlayerName", name);
}
}
using EasyTransition;
using Unity.VectorGraphics;
using UnityEngine;
using UnityEngine.SceneManagement;
public class ChangeSceneManager : MonoBehaviour
{
public static ChangeSceneManager Instance { get; private set; }
[SerializeField] TransitionSettings transitionSettings;
private void Awake()
{
if (Instance == null)
Instance = this;
else
Destroy(this);
}
void Change(string sceneName)
{
// TransitionManager.Instance().Transition(sceneName, transitionSettings,0);
SceneManager.LoadScene(sceneName);
}
void Change(int sceneIndex)
{
// TransitionManager.Instance().Transition(sceneName, transitionSettings,0);
SceneManager.LoadScene(sceneIndex);
}
public void ChangeToLobbyScene()
{
Change("LobbyScene");
}
public void ChangeToMainmenuScene()
{
Change("MainMenu");
}
}
......@@ -5,13 +5,16 @@ using UnityEngine;
public class HandlePlayersConnection : NetworkBehaviour
{
[SerializeField] int maxPlayer;
[SerializeField] GameManager gameManagerScript;
[SerializeField] GameManager gameManagerScript;
[SerializeField] Fade fadeScript;
[SerializeField] ApprovRequest approvRequest;
[SerializeField] NetworkObject playerPrefab;
[SerializeField] NetworkObject npcPrefab;
[SerializeField] Transform npcParent;
ApprovRequest _approvRequest;
public override void OnNetworkSpawn()
{
approvRequest = ApprovRequest.Instance;
{
_approvRequest = ApprovRequest.Instance;
StartCoroutine(SpawnPlayer());
}
......@@ -21,20 +24,35 @@ public class HandlePlayersConnection : NetworkBehaviour
yield return new WaitForSeconds(3);
if (IsServer)
{
foreach (var item in approvRequest.clientData)
foreach (var _player in _approvRequest.clientData)
{
PlayerNetworkData playerData = new PlayerNetworkData
{
PlayerAuthId = item.Value.AuthId,
playerName = item.Value.playerName,
PlayerAvatar = int.Parse(item.Value.playerAvatar),
PlayerAuthId = _player.Value.AuthId,
playerName = _player.Value.playerName,
PlayerAvatar = _player.Value.playerAvatar,
};
NetworkObject player = Instantiate(approvRequest.playerPrefab);
player.SpawnAsPlayerObject(item.Key);
NetworkObject player = Instantiate(playerPrefab);
player.SpawnAsPlayerObject(_player.Key);
player.GetComponent<PlayerDetails>().InitPlayerData(playerData);
}
foreach (var npc in _approvRequest.npctData)
{
PlayerNetworkData playerData = new PlayerNetworkData
{
PlayerAuthId = npc.Value.clientId.ToString(),
playerName = npc.Value.playerName,
PlayerAvatar = npc.Value.playerAvatar,
};
NetworkObject npcObject = Instantiate(npcPrefab,npcParent.transform);
npcObject.Spawn();
npcObject.GetComponent<PlayerDetails>().InitPlayerData(playerData);
}
}
gameManagerScript.StartMatch();
fadeScript.FadeOut();
}
......
using System;
using System.Collections.Generic;
using System.Text;
using Unity.Netcode;
using Unity.Services.Authentication;
using Unity.Services.Lobbies.Models;
using UnityEngine;
using UnityEngine.SceneManagement;
public class ApprovRequest : MonoBehaviour
{
public static ApprovRequest Instance;
public Dictionary<ulong, PlayerData> clientData { get; private set; } = new Dictionary<ulong, PlayerData>();
[field: SerializeField] public NetworkObject playerPrefab { get; private set; }
public Dictionary<ulong, PlayerLobbyData> npctData { get; private set; } = new Dictionary<ulong, PlayerLobbyData>();
NetworkManager _networkManager;
private void Awake()
{
if (Instance == null)
......@@ -27,16 +27,67 @@ public class ApprovRequest : MonoBehaviour
{
_networkManager = NetworkManager.Singleton;
_networkManager.ConnectionApprovalCallback = ApprovConnection;
_networkManager.OnServerStarted += OnServerReady;
}
private void OnServerReady()
{
_networkManager.OnClientDisconnectCallback += OnClientDisconnect;
}
private void OnClientDisconnect(ulong clientId)
{
if (clientData.ContainsKey(clientId))
{
clientData.Remove(clientId);
}
}
private void ApprovConnection(NetworkManager.ConnectionApprovalRequest request, NetworkManager.ConnectionApprovalResponse response)
{
string bytes = Encoding.UTF8.GetString(request.Payload);
PlayerData playerData = JsonUtility.FromJson<PlayerData>(bytes);
clientData[request.ClientNetworkId] = playerData;
if (!clientData.ContainsKey(request.ClientNetworkId))
{
clientData[request.ClientNetworkId] = playerData;
}
response.Approved = true;
response.CreatePlayerObject = false;
}
public void CreatePlayerDataObject()
{
string AuthId = AuthenticationService.Instance.PlayerId;
Player player = LobbyRequest._currentLobby.Players.Find(p => p.Id == AuthId);
PlayerData playerData = new PlayerData
{
AuthId = AuthId,
playerName = PlayerPrefs.GetString("PlayerName"),
playerAvatar = Random.Range(1, 4),
};
AddDataToConnection(playerData);
}
}
public void AddDataToConnection(PlayerData playerData)
{
string data = JsonUtility.ToJson(playerData);
byte[] dataToByte = Encoding.UTF8.GetBytes(data);
_networkManager.NetworkConfig.ConnectionData = dataToByte;
}
public async void LeavePlayer()
{
if (_networkManager.IsServer)
{
_networkManager.SceneManager.LoadScene("MainMenu", LoadSceneMode.Single);
await LobbyRequest.RemoveLobby();
Destroy(LobbyHeart.Instance.gameObject);
clientData.Clear();
}
else
{
await LobbyRequest.RemovePlayerFromLobby(AuthenticationService.Instance.PlayerId);
SceneManager.LoadScene(0);
}
_networkManager.Shutdown();
}
}
\ No newline at end of file
......@@ -5,5 +5,5 @@ public class PlayerData
{
public string AuthId;
public string playerName;
public string playerAvatar;
public int playerAvatar;
}
using TMPro;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using TMPro;
using Unity.Netcode;
using Unity.Services.Lobbies;
using Unity.Services.Lobbies.Models;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic;
using Unity.Services.Lobbies.Models;
using Unity.Netcode;
using System;
public class CreateLobby : MonoBehaviour
{
[SerializeField] TMP_InputField lobbyNameInput;
[SerializeField] Toggle lobbyPriveteToggle;
[SerializeField] Button CreateLobbyButton;
[SerializeField] int maxPlayers;
FadeWithText _fadeWithText;
private void Start()
{
CreateLobbyButton.onClick.AddListener(Create);
CreateLobbyButton.onClick.AddListener(CreateGame);
_fadeWithText = FadeWithText.Instance;
}
async void CreateGame()
{
CreateLobbyButton.interactable = false;
bool isCreated = await CreateLobbyAndRelay();
CreateLobbyButton.interactable = true;
if (isCreated)
{
_fadeWithText.ShowMessage("جاري دخول الغرفة...", false);
NetworkManager networkManager = NetworkManager.Singleton;
RelayRequest.CreateAllocation(networkManager);
ApprovRequest approvRequest = ApprovRequest.Instance;
approvRequest.CreatePlayerDataObject();
networkManager.StartHost();
networkManager.SceneManager.LoadScene("LobbyScene", UnityEngine.SceneManagement.LoadSceneMode.Single);
}
}
private async void Create()
private async Task<bool> CreateLobbyAndRelay()
{
if (!string.IsNullOrEmpty(lobbyNameInput.text))
if (string.IsNullOrWhiteSpace(lobbyNameInput.text))
{
CreateLobbyButton.interactable = false;
_fadeWithText.ShowMessage("جاري التحميل...", false);
bool createLobby = await LobbyRequest.Create(lobbyNameInput.text, 4, LobbyOptions());
if (createLobby)
{
ChangeSceneManager.Instance.ChangeToLobbyScene();
}
else
{
CreateLobbyButton.interactable = true;
FadeWithText.Instance.ShowMessage("حدث خطأ", true);
}
}
else
_fadeWithText.ShowMessage("من فضلك ادخل اسم الغرفة", true);
return false;
}
_fadeWithText.ShowMessage("جاري إنشاء الغرفة...", false);
string relayCode = await RelayRequest.CreateLobbyCode(maxPlayers);
bool lobbyCreated = await LobbyRequest.Create(lobbyNameInput.text, maxPlayers, LobbyOptions(relayCode));
if (!lobbyCreated)
{
FadeWithText.Instance.ShowMessage("حدث خطأ أثناء إنشاء الغرفة", true);
return false;
}
return true;
}
CreateLobbyOptions LobbyOptions()
private CreateLobbyOptions LobbyOptions(string relayCode)
{
CreateLobbyOptions lobbyOptions = new CreateLobbyOptions();
lobbyOptions.IsPrivate = lobbyPriveteToggle.isOn;
lobbyOptions.Data = new Dictionary<string, DataObject>
{
{"AllocationCode",new DataObject(visibility: DataObject.VisibilityOptions.Member,value:"") },
{"RelayCode",new DataObject(visibility: DataObject.VisibilityOptions.Public,value:relayCode) },
{"NPCsCount", new DataObject(visibility:DataObject.VisibilityOptions.Public,value:"0") },
};
return lobbyOptions;
......
using System;
using System.Threading.Tasks;
using TMPro;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.UI;
public class JoinLobbyByCode : MonoBehaviour
{
[SerializeField] TMP_InputField lobbyCodeInput;
[SerializeField] Button createLobbyButton;
[SerializeField] Button createLobbyButton;
void Start()
{
createLobbyButton.onClick.AddListener(Join);
......@@ -18,20 +19,32 @@ public class JoinLobbyByCode : MonoBehaviour
if (!string.IsNullOrEmpty(lobbyCodeInput.text))
{
createLobbyButton.interactable = false;
FadeWithText.Instance.ShowMessage("جاري التحميل", false);
bool join = await LobbyRequest.JoinLobbyByCode(lobbyCodeInput.text);
if (join)
FadeWithText.Instance.ShowMessage("جاري التحميل...", false);
string relayCode = await LobbyRequest.JoinLobbyByCode(lobbyCodeInput.text);
if (!string.IsNullOrEmpty(relayCode))
{
ChangeSceneManager.Instance.ChangeToLobbyScene();
NetworkManager networkManager = NetworkManager.Singleton;
FadeWithText.Instance.ShowMessage("جاري الدخول الي الغرفة...", false);
bool joinToServer = await RelayRequest.JoinAllocation(networkManager, relayCode);
if (joinToServer)
{
ApprovRequest.Instance.CreatePlayerDataObject();
networkManager.StartClient();
}
else
{
FadeWithText.Instance.ShowMessage("حدث خطأ أثناء الإنضمام الي الغرفة", true);
}
}
else
{
createLobbyButton.interactable = true;
FadeWithText.Instance.ShowMessage("الرقم غير صحيح", true);
}
}
else
FadeWithText.Instance.ShowMessage("من فضلك ادخل رقم الغرفة", true);
createLobbyButton.interactable = false;
}
}
using System;
using Unity.Collections;
using Unity.Netcode;
public struct PlayerLobbyData : INetworkSerializable,IEquatable<PlayerLobbyData>
{
public ulong clientId;
public FixedString32Bytes playerName;
public int playerAvatar;
public bool isReady;
public bool isNPC;
public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
{
serializer.SerializeValue(ref clientId);
serializer.SerializeValue(ref playerName);
serializer.SerializeValue(ref playerAvatar);
serializer.SerializeValue(ref isReady);
serializer.SerializeValue(ref isNPC);
}
public bool Equals(PlayerLobbyData other)
{
return other.clientId == clientId && other.playerName == playerName && other.playerAvatar == playerAvatar && other.isReady == isReady && other.isNPC == isNPC;
}
}
fileFormatVersion: 2
guid: bd7addcbfc2b864408bfe3400dbe7059
\ No newline at end of file
guid: 94a7483b108326f4d9042c734f9c6a38
\ No newline at end of file
fileFormatVersion: 2
guid: 3e56ca6796df8164c946c1e398109b90
guid: 77703a9ec39769c479332c9d6455f3d8
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
......
using System;
using System.Threading.Tasks;
using TMPro;
using TMPro;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.UI;
......@@ -10,32 +9,47 @@ public class LobbyDetails : MonoBehaviour
[SerializeField] TextMeshProUGUI lobbyPlayersCountText;
[SerializeField] Button joinLobbyButton;
string _joinCode;
string _lobbyCode;
string _relayCode;
private void Start()
{
joinLobbyButton.onClick.AddListener(joinLobby);
}
public void AddDetailsToLobby(string lobbyName, string lobbyPlayersCount, string lobbyCode, string relayCode)
{
lobbyNameText.text = lobbyName;
lobbyPlayersCountText.text = lobbyPlayersCount;
_lobbyCode = lobbyCode;
_relayCode = relayCode;
}
private async void joinLobby()
{
joinLobbyButton.interactable = false;
FadeWithText.Instance.ShowMessage("جاري التحميل", false);
bool join = await LobbyRequest.JoinLobby(_joinCode);
FadeWithText.Instance.ShowMessage("جاري التحميل...", false);
bool join = await LobbyRequest.JoinLobby(_lobbyCode);
if (join) {
ChangeSceneManager.Instance.ChangeToLobbyScene();
}
NetworkManager networkManager = NetworkManager.Singleton;
FadeWithText.Instance.ShowMessage("جاري الدخول الي الغرفة...", false);
bool joinToServer = await RelayRequest.JoinAllocation(networkManager, _relayCode);
if (joinToServer)
{
ApprovRequest.Instance.CreatePlayerDataObject();
networkManager.StartClient();
}
else
{
FadeWithText.Instance.ShowMessage("حدث خطأ أثناء الاتصال بالخادم", true);
}
}
else
{
joinLobbyButton.interactable = true;
FadeWithText.Instance.ShowMessage("حدث خطأ", true);
FadeWithText.Instance.ShowMessage("حدث خطأ أثناء الانضمام الي الغرفة", true);
}
}
public void AddDetailsToLobby(string lobbyName, string lobbyPlayersCount, string joinCode)
{
lobbyNameText.text = lobbyName;
lobbyPlayersCountText.text = lobbyPlayersCount;
this._joinCode = joinCode;
}
}
......@@ -29,12 +29,9 @@ public class LobbyList : MonoBehaviour
int npcCounter = int.Parse(lobby.Data["NPCsCount"].Value.ToString()) + lobby.Players.Count;
string playersCount = $"{npcCounter}/{lobby.MaxPlayers}";
lobbyDetails.AddDetailsToLobby(lobby.Name, playersCount, lobby.Id);
lobbyDetails.gameObject.SetActive(npcCounter < lobby.MaxPlayers);
lobbyDetails.AddDetailsToLobby(lobby.Name, playersCount, lobby.Id, lobby.Data["RelayCode"].Value);
}
StartCoroutine(FadeOutAfterDelay());
}
private IEnumerator FadeOutAfterDelay()
......
using System;
using TMPro;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.UI;
public class LobbySlot : MonoBehaviour
{
[SerializeField] TextMeshProUGUI playerName;
[SerializeField] Image avatarImage;
[SerializeField] Button readyButton;
[SerializeField] Button removeButton;
LobbyRoom _lobbyRoom;
ulong _slotId;
bool _isNPC;
bool _isBusy;
private void Start()
{
readyButton.onClick.AddListener(Ready);
removeButton.onClick.AddListener(RemoveNpc);
_lobbyRoom = FindAnyObjectByType<LobbyRoom>();
}
public void AddData(PlayerLobbyData playerLobbyData)
{
_isBusy = true;
bool localClient = NetworkManager.Singleton.LocalClientId == playerLobbyData.clientId;
bool npc = playerLobbyData.isNPC && NetworkManager.Singleton.IsServer;
removeButton.gameObject.SetActive(npc);
_slotId = playerLobbyData.clientId;
_isNPC = playerLobbyData.isNPC;
readyButton.interactable = localClient || npc && !_isBusy;
removeButton.interactable = localClient || npc;
ChangeAvatar(playerLobbyData.playerAvatar);
playerName.text = playerLobbyData.playerName.ToString();
Color btnColor;
string btnText;
if (playerLobbyData.isReady)
{
btnColor = Color.green;
btnText = "Is Ready";
}
else
{
btnColor = Color.white;
btnText = "Ready";
}
readyButton.GetComponent<Image>().color = btnColor;
readyButton.GetComponentInChildren<TextMeshProUGUI>().text = btnText;
}
void ChangeAvatar(int index)
{
avatarImage.sprite = GetComponentInParent<AvatarMenu>().GetSpriteByIndex(index);
}
private void Ready()
{
_lobbyRoom.IsButtonClicked(_slotId,_isBusy);
}
private void RemoveNpc()
{
_lobbyRoom.RemoveRpc(_slotId);
}
public void ClearData()
{
ChangeAvatar(0);
readyButton.GetComponent<Image>().color = Color.white;
readyButton.GetComponentInChildren<TextMeshProUGUI>().text = "Add NPC";
playerName.text = " ";
_isNPC = false;
_isBusy = false;
// removeButton.gameObject.SetActive(false);
_slotId = (ulong)0000;
readyButton.interactable = NetworkManager.Singleton.IsServer;
removeButton.gameObject.SetActive(false);
}
}
fileFormatVersion: 2
guid: c574610257016cb4ea3bcbc2fd758e50
\ No newline at end of file
guid: 6a78fdea850e51e419140ed5165632a8
\ No newline at end of file
using System;
using System.Threading.Tasks;
using TMPro;
using Unity.Services.Authentication;
using Unity.Services.Lobbies;
using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic;
using Unity.Services.Lobbies.Models;
public class PlayersInLobbyRoom : MonoBehaviour
{
[field: SerializeField] public bool isBusySlot { get; private set; }
[SerializeField] TextMeshProUGUI playerName;
[SerializeField] Image avatarImage;
[SerializeField] Button readyButton;
string _playerId;
bool _isNPC;
bool _isOwner;
private void Start()
{
readyButton.onClick.AddListener(Ready);
}
public void SetIsOwner(bool isOwner)
{
_isOwner = isOwner;
}
private async void Ready()
{
if (isBusySlot && !_isNPC)
{
UpdatePlayerOptions updatePlayerOptions = new UpdatePlayerOptions();
updatePlayerOptions.Data = new Dictionary<string, PlayerDataObject>
{
{"IsReady", new PlayerDataObject(PlayerDataObject.VisibilityOptions.Member, "True")}
};
await LobbyRequest.UpdatePlayerData(_playerId, updatePlayerOptions);
}
else if (!isBusySlot && !_isNPC)
{
await AddNPC();
}
else if (_isNPC && _isOwner)
{
await RemoveNPC();
}
}
async Task AddNPC()
{
try
{
UpdateLobbyOptions updateLobbyOptions = new UpdateLobbyOptions()
{
Data = new Dictionary<string, DataObject>
{
{"NPCsCount", new DataObject(visibility: DataObject.VisibilityOptions.Public, value: (GetCurrentNPCCount() + 1).ToString())}
}
};
await LobbyRequest.UpdateLobby(updateLobbyOptions);
InitializeAsNPC();
}
catch (Exception ex)
{
Debug.LogException(ex);
}
}
async Task RemoveNPC()
{
try
{
int currentCount = GetCurrentNPCCount();
int newCount = Mathf.Max(0, currentCount - 1);
UpdateLobbyOptions updateLobbyOptions = new UpdateLobbyOptions()
{
Data = new Dictionary<string, DataObject>
{
{"NPCsCount", new DataObject(visibility: DataObject.VisibilityOptions.Public, value: newCount.ToString())}
}
};
await LobbyRequest.UpdateLobby(updateLobbyOptions);
Clear();
Debug.Log("NPC Removed Successfully");
}
catch (Exception ex)
{
Debug.LogError($"Error removing NPC: {ex}");
}
}
public void InitializeAsNPC()
{
_isNPC = true;
isBusySlot = true;
ChangeAvatar(3);
playerName.text = "NPC#" + UnityEngine.Random.Range(1000, 9999);
readyButton.interactable = _isOwner;
readyButton.image.color = Color.red;
readyButton.GetComponentInChildren<TextMeshProUGUI>().text = "Remove";
readyButton.GetComponentInChildren<TextMeshProUGUI>().color = Color.white;
}
public void Init(string name, string avatarIndex, string playerId, string isReady)
{
_isNPC = false;
ChangeAvatar(int.Parse(avatarIndex));
playerName.text = name;
isBusySlot = true;
this._playerId = playerId;
readyButton.interactable = playerId == AuthenticationService.Instance.PlayerId;
readyButton.GetComponentInChildren<TextMeshProUGUI>().text = "Ready";
if (isReady == "True")
{
readyButton.GetComponentInChildren<TextMeshProUGUI>().text = "Is Ready";
readyButton.interactable = false;
readyButton.image.color = Color.green;
}
}
public void SetNPC(bool isOwner)
{
if (isOwner && !isBusySlot && !_isNPC)
{
readyButton.interactable = true;
readyButton.GetComponentInChildren<TextMeshProUGUI>().text = "Add NPCs";
}
}
public void Clear()
{
isBusySlot = false;
_isNPC = false;
_playerId = "";
playerName.text = "";
ChangeAvatar(0);
readyButton.interactable = false;
readyButton.GetComponentInChildren<TextMeshProUGUI>().text = "";
readyButton.GetComponentInChildren<TextMeshProUGUI>().color = Color.black;
readyButton.image.color = Color.white;
}
void ChangeAvatar(int index)
{
avatarImage.sprite = GetComponentInParent<AvatarMenu>().GetSpriteByIndex(index);
}
private int GetCurrentNPCCount()
{
try
{
if (LobbyRequest._currentLobby.Data.ContainsKey("NPCsCount"))
{
return int.Parse(LobbyRequest._currentLobby.Data["NPCsCount"].Value);
}
}
catch
{
return 0;
}
return 0;
}
}
\ No newline at end of file
......@@ -2,9 +2,16 @@ using UnityEngine;
public class LobbyHeart : MonoBehaviour
{
public static LobbyHeart Instance;
Coroutine _heartCoroutine;
private void Awake()
{
if (Instance == null)
Instance = this;
else
Destroy(this);
DontDestroyOnLoad(gameObject);
}
private void Start()
......
......@@ -12,12 +12,9 @@ public static class LobbyRequest
public static Lobby _currentLobby { get; private set; }
public static async Task<bool> Create(string lobbyName, int maxPlayer, CreateLobbyOptions createLobbyOptions)
{
createLobbyOptions.Player = SetPlayerData();
try
{
_currentLobby = await LobbyService.Instance.CreateLobbyAsync(lobbyName, maxPlayer, createLobbyOptions);
SetPlayerPrefs();
new GameObject("LobbyHeart").AddComponent<LobbyHeart>();
return true;
}
......@@ -67,9 +64,7 @@ public static class LobbyRequest
{
try
{
JoinLobbyByIdOptions joinLobbyByIdOptions = new JoinLobbyByIdOptions() { Player = SetPlayerData() };
_currentLobby = await LobbyService.Instance.JoinLobbyByIdAsync(joinCode, joinLobbyByIdOptions);
SetPlayerPrefs();
_currentLobby = await LobbyService.Instance.JoinLobbyByIdAsync(joinCode);
return true;
}
catch (LobbyServiceException ex)
......@@ -82,9 +77,10 @@ public static class LobbyRequest
}
return false;
}
public static async void RemovePlayerFromLobby(string playerId)
public static async Task RemovePlayerFromLobby(string playerId)
{
if (_currentLobby == null) return;
Debug.Log("Remmove");
try
{
if (playerId == AuthenticationService.Instance.PlayerId)
......@@ -103,7 +99,7 @@ public static class LobbyRequest
Debug.LogException(ex);
}
}
public static async void RemoveLobby()
public static async Task RemoveLobby()
{
if (_currentLobby == null) return;
......@@ -122,15 +118,12 @@ public static class LobbyRequest
}
}
public static async Task<bool> JoinLobbyByCode(string lobbyCode)
public static async Task<string> JoinLobbyByCode(string lobbyCode)
{
try
{
JoinLobbyByCodeOptions joinLobbyByCodeOptions = new JoinLobbyByCodeOptions() { Player = SetPlayerData() };
_currentLobby = await LobbyService.Instance.JoinLobbyByCodeAsync(lobbyCode, joinLobbyByCodeOptions);
SetPlayerPrefs();
return true;
_currentLobby = await LobbyService.Instance.JoinLobbyByCodeAsync(lobbyCode);
return _currentLobby.Data["RelayCode"].Value;
}
catch (LobbyServiceException ex)
{
......@@ -140,66 +133,9 @@ public static class LobbyRequest
{
Debug.LogException(ex);
}
return false;
return string.Empty;
}
public static async Task UpdatePlayerData(string playerId, UpdatePlayerOptions updatePlayerOptions)
{
try
{
await LobbyService.Instance.UpdatePlayerAsync(_currentLobby.Id, playerId, updatePlayerOptions);
}
catch (LobbyServiceException ex)
{
Debug.LogException(ex);
}
catch (Exception ex)
{
Debug.LogException(ex);
}
}
public static async Task UpdateLobby(UpdateLobbyOptions updateLobbyOptions)
{
try
{
await LobbyService.Instance.UpdateLobbyAsync(_currentLobby.Id, updateLobbyOptions);
}
catch (LobbyServiceException ex)
{
Debug.LogException(ex);
}
catch (Exception ex)
{
Debug.LogException(ex);
}
}
static Player SetPlayerData()
{
Player player = new Player(
id: AuthenticationService.Instance.PlayerId,
data: new Dictionary<string, PlayerDataObject>
{
{
"Name",
new PlayerDataObject(
PlayerDataObject.VisibilityOptions.Member,
"Player#" + UnityEngine.Random.Range(1000,9999)
)
},
{
"AvatarIndex",
new PlayerDataObject(PlayerDataObject.VisibilityOptions.Member,"1")
},
{"IsReady",
new PlayerDataObject(PlayerDataObject.VisibilityOptions.Member,"False")
}
}
);
return player;
}
static void SetPlayerPrefs()
{
PlayerPrefs.SetString("JoinCode", _currentLobby.LobbyCode);
}
}
using System;
using System.Threading.Tasks;
using Unity.Netcode;
using Unity.Netcode.Transports.UTP;
using Unity.Networking.Transport.Relay;
using Unity.Services.Relay;
using Unity.Services.Relay.Models;
using UnityEngine;
public static class AllocationRequest
public static class RelayRequest
{
public static Allocation _allocation;
public static async Task<string> Create()
public static async Task<string> CreateLobbyCode(int playerCount)
{
try
{
_allocation = await RelayService.Instance.CreateAllocationAsync(4);
_allocation = await RelayService.Instance.CreateAllocationAsync(playerCount);
}
catch (Exception ex)
{
......@@ -27,4 +30,26 @@ public static class AllocationRequest
}
return string.Empty;
}
public static void CreateAllocation(NetworkManager networkManager)
{
UnityTransport unityTransport = networkManager.GetComponent<UnityTransport>();
RelayServerData relayServerData = AllocationUtils.ToRelayServerData(_allocation, "wss");
unityTransport.SetRelayServerData(relayServerData);
}
public static async Task<bool> JoinAllocation(NetworkManager networkManager,string joinCode)
{
try
{
UnityTransport unityTransport = networkManager.GetComponent<UnityTransport>();
JoinAllocation joinCodeData = await RelayService.Instance.JoinAllocationAsync(joinCode);
RelayServerData relayServerData = AllocationUtils.ToRelayServerData(joinCodeData, "wss");
unityTransport.SetRelayServerData(relayServerData);
return true;
}
catch (Exception ex)
{
Debug.LogException(ex);
return false;
}
}
}
......@@ -10,8 +10,6 @@ public class PlayerDetails : NetworkBehaviour
public NetworkVariable<FixedString32Bytes> PlayerName = new NetworkVariable<FixedString32Bytes>("Null", readPerm: NetworkVariableReadPermission.Everyone, writePerm: NetworkVariableWritePermission.Owner);
[SerializeField] bool isNPC;
[SerializeField] RTLTextMeshPro nameText;
[SerializeField] string avatar;
public void InitPlayerData(PlayerNetworkData playerNetworkData)
......
......@@ -11,7 +11,7 @@ public class LeaderboardUI : NetworkBehaviour
Dictionary<ulong, LeaderboardText> leaderboardUIElements = new Dictionary<ulong, LeaderboardText>();
ApprovRequest approvRequest;
[SerializeField] ApprovRequest approvRequest;
public override void OnNetworkSpawn()
{
......
......@@ -10,13 +10,10 @@ EditorBuildSettings:
guid: 9a357ab131db7bd4d8e56aa52459b9a4
- enabled: 1
path: Assets/_project/Scenes/LobbyScene.unity
guid: 352bf19a87eb5f84da505d6b76a39310
guid: 3e56ca6796df8164c946c1e398109b90
- enabled: 1
path: Assets/_project/Scenes/Game.unity
guid: ed75d94d1c2d6934f9aa9556db95a098
- enabled: 1
path: Assets/_project/Scenes/NewLobby.unity
guid: 3e56ca6796df8164c946c1e398109b90
m_configObjects:
com.unity.input.settings.actions: {fileID: -944628639613478452, guid: 052faaac586de48259a63d0c4782560b, type: 3}
m_UseUCBPForAssetBundles: 0
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment