diff --git a/.gitignore b/.gitignore index 2046667..b6f9015 100644 --- a/.gitignore +++ b/.gitignore @@ -82,3 +82,5 @@ Assets/Plugins Assets/PlayroomKit/node_modules.meta /.idea Assets/chromedriver* +Assets/msedgedriver.exe +Assets/msedgedriver.exe.meta diff --git a/Assets/PlayroomKit/Editor/PlayroomDevEditor.cs b/Assets/PlayroomKit/Editor/PlayroomDevEditor.cs index 5bbd01e..070c290 100644 --- a/Assets/PlayroomKit/Editor/PlayroomDevEditor.cs +++ b/Assets/PlayroomKit/Editor/PlayroomDevEditor.cs @@ -15,6 +15,11 @@ public class PrkMockInspector : Editor { public StyleSheet styleSheet; + public void OnEnable() + { + styleSheet = AssetDatabase.LoadAssetAtPath("Assets/PlayroomKit/Editor/PlayroomkitDevManagerEditor.uss"); + } + public override VisualElement CreateInspectorGUI() { VisualElement root = new VisualElement @@ -24,6 +29,12 @@ public override VisualElement CreateInspectorGUI() flexDirection = FlexDirection.Column } }; + + if (styleSheet == null) + { + Debug.LogError("Style sheet is null"); + } + root.styleSheets.Add(styleSheet); VisualElement mockModeContainer = MockModeContainerCreator(); @@ -112,7 +123,7 @@ private VisualElement MockModeContainerCreator() var mockModeOptions = new List { "Local (simulated)", - // "Browser Bridge (live)" + "Browser Bridge (live)" }; var mockModeProperty = serializedObject.FindProperty("mockMode"); @@ -128,16 +139,16 @@ private VisualElement MockModeContainerCreator() mockModeDropdown.RegisterValueChangedCallback(evt => { var selectedString = evt.newValue; - PlayroomKit.MockModeSelector selectedEnum = PlayroomKit.MockModeSelector.Local; // Default value + PlayroomKit.MockModeSelector selectedEnum = PlayroomKit.MockModeSelector.Local; if (selectedString == "Local (simulated)") { selectedEnum = PlayroomKit.MockModeSelector.Local; } - // else if (selectedString == "Browser Bridge (live)") - // { - // selectedEnum = PlayroomKit.MockModeSelector.BrowserBridge; - // } + else if (selectedString == "Browser Bridge (live)") + { + selectedEnum = PlayroomKit.MockModeSelector.Browser; + } mockModeProperty.enumValueIndex = (int)selectedEnum; serializedObject.ApplyModifiedProperties(); diff --git a/Assets/PlayroomKit/Examples/2d-platformer/2d-platformer.unity b/Assets/PlayroomKit/Examples/2d-platformer/2d-platformer.unity index 0422634..34f52d2 100644 --- a/Assets/PlayroomKit/Examples/2d-platformer/2d-platformer.unity +++ b/Assets/PlayroomKit/Examples/2d-platformer/2d-platformer.unity @@ -307,6 +307,18 @@ PrefabInstance: propertyPath: insertCoinCaller value: objectReference: {fileID: 330732768} + - target: {fileID: 8899696337967424923, guid: 1b30fa3a265114a45a7e23165a20aecc, type: 3} + propertyPath: webDriverDirectory + value: Assets\ + objectReference: {fileID: 0} + - target: {fileID: 8987662522597341863, guid: 1b30fa3a265114a45a7e23165a20aecc, type: 3} + propertyPath: mockMode + value: 1 + objectReference: {fileID: 0} + - target: {fileID: 8987662522597341863, guid: 1b30fa3a265114a45a7e23165a20aecc, type: 3} + propertyPath: insertCoinCaller + value: + objectReference: {fileID: 330732768} m_RemovedComponents: [] m_RemovedGameObjects: [] m_AddedGameObjects: [] diff --git a/Assets/PlayroomKit/Examples/2d-platformer/scripts/GameManager2d.cs b/Assets/PlayroomKit/Examples/2d-platformer/scripts/GameManager2d.cs index 26a2c2a..8da38b9 100644 --- a/Assets/PlayroomKit/Examples/2d-platformer/scripts/GameManager2d.cs +++ b/Assets/PlayroomKit/Examples/2d-platformer/scripts/GameManager2d.cs @@ -73,7 +73,7 @@ void Start() /// void HandleScoreUpdate(string data, string caller) { - var player = PlayroomKit.GetPlayer(caller); + var player = _playroomKit.GetPlayer(caller); Debug.Log($"Caller: {caller}, Player Name: {player?.GetProfile().name}, Data: {data}"); if (PlayerDict.TryGetValue(caller, out GameObject playerObj)) diff --git a/Assets/PlayroomKit/Examples/discord-activity/discord-activity.unity b/Assets/PlayroomKit/Examples/discord-activity/discord-activity.unity index afc63d3..663db6b 100644 --- a/Assets/PlayroomKit/Examples/discord-activity/discord-activity.unity +++ b/Assets/PlayroomKit/Examples/discord-activity/discord-activity.unity @@ -38,7 +38,7 @@ RenderSettings: m_ReflectionIntensity: 1 m_CustomReflection: {fileID: 0} m_Sun: {fileID: 1429187865} - m_IndirectSpecularColor: {r: 0.44657815, g: 0.49641192, b: 0.5748165, a: 1} + m_IndirectSpecularColor: {r: 0.44657844, g: 0.49641222, b: 0.57481694, a: 1} m_UseRadianceAmbientProbe: 0 --- !u!157 &3 LightmapSettings: @@ -343,6 +343,18 @@ PrefabInstance: propertyPath: insertCoinCaller value: objectReference: {fileID: 1903050736} + - target: {fileID: 8899696337967424923, guid: 1b30fa3a265114a45a7e23165a20aecc, type: 3} + propertyPath: browser + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 8899696337967424923, guid: 1b30fa3a265114a45a7e23165a20aecc, type: 3} + propertyPath: webDriverDirectory + value: Assets\ + objectReference: {fileID: 0} + - target: {fileID: 8987662522597341863, guid: 1b30fa3a265114a45a7e23165a20aecc, type: 3} + propertyPath: insertCoinCaller + value: + objectReference: {fileID: 1903050736} m_RemovedComponents: [] m_RemovedGameObjects: [] m_AddedGameObjects: [] diff --git a/Assets/PlayroomKit/Examples/discord-activity/scripts/GameManagerIsometric.cs b/Assets/PlayroomKit/Examples/discord-activity/scripts/GameManagerIsometric.cs index 3379d8c..08f454a 100644 --- a/Assets/PlayroomKit/Examples/discord-activity/scripts/GameManagerIsometric.cs +++ b/Assets/PlayroomKit/Examples/discord-activity/scripts/GameManagerIsometric.cs @@ -12,9 +12,12 @@ public class GameManagerIsometric : MonoBehaviour private static readonly Dictionary PlayerDict = new(); - [SerializeField] private static bool playerJoined; - [SerializeField] private string roomCode; - [SerializeField] private GameObject playerPrefab; + [SerializeField] + private static bool playerJoined; + [SerializeField] + private string roomCode; + [SerializeField] + private GameObject playerPrefab; private PlayroomKit _playroomKit = new PlayroomKit(); @@ -24,8 +27,8 @@ private void Start() { maxPlayersPerRoom = 3, matchmaking = false, - gameId = "", discord = true, + gameId = "ii4pV1wfceCjjLvRoo3O", roomCode = roomCode, }, () => { _playroomKit.OnPlayerJoin(AddPlayer); }, () => { Debug.Log("OnDisconnect callback"); }); } @@ -40,8 +43,7 @@ private void Update() playerGameObjects[index].GetComponent().LookAround(); players[index].SetState("angle", playerGameObjects[index].GetComponent().rotation); - - + playerGameObjects[index].GetComponent().Move(); players[index].SetState("move", playerGameObjects[index].GetComponent().position); @@ -66,6 +68,8 @@ private void Update() public void AddPlayer(PlayroomKit.Player player) { + Debug.LogFormat("{0} Is host?: {1}", player.GetProfile().name,_playroomKit.IsHost()); + var playerObj = Instantiate(playerPrefab, new Vector3(Random.Range(-5, 5), 2f, Random.Range(-5, 5)), Quaternion.identity); diff --git a/Assets/PlayroomKit/Examples/package-showcase/scripts/GameManagerDemo.cs b/Assets/PlayroomKit/Examples/package-showcase/scripts/GameManagerDemo.cs index 7da3020..bcc79ea 100644 --- a/Assets/PlayroomKit/Examples/package-showcase/scripts/GameManagerDemo.cs +++ b/Assets/PlayroomKit/Examples/package-showcase/scripts/GameManagerDemo.cs @@ -10,18 +10,24 @@ public class GameManagerDemo : MonoBehaviour { private static readonly List players = new(); private static readonly List playerGameObjects = new(); - private static readonly Dictionary PlayerDict = new(); - [SerializeField] private static bool playerJoined; - [SerializeField] private string roomCode; - [SerializeField] private GameObject playerPrefab; - [SerializeField] private int score; + [SerializeField] + private static bool playerJoined; + [SerializeField] + private string roomCode; + [SerializeField] + private GameObject playerPrefab; + [SerializeField] + private int score; [Header("UI")] - [SerializeField] private TMP_Dropdown getDropDown; - [SerializeField] private TMP_Dropdown colorDropDown; - [SerializeField] private TextMeshProUGUI logsText; + [SerializeField] + private TMP_Dropdown getDropDown; + [SerializeField] + private TMP_Dropdown colorDropDown; + [SerializeField] + private TextMeshProUGUI logsText; private PlayroomKit _playroomKit = new(); @@ -39,11 +45,11 @@ private void Update() } } - public void InsertCoin() { _playroomKit.InsertCoin(new InitOptions { + skipLobby = true, maxPlayersPerRoom = 3, matchmaking = false, roomCode = roomCode @@ -240,7 +246,7 @@ public void RegisterRpcShoot() private void HandleScoreUpdate(string data, string caller) { - var player = PlayroomKit.GetPlayer(caller); + var player = _playroomKit.GetPlayer(caller); Debug.Log($"Caller: {caller}, Player Name: {player?.GetProfile().name}, Data: {data}"); if (PlayerDict.TryGetValue(caller, out var playerObj)) @@ -286,7 +292,7 @@ public void IsHost() logsText.text = $"{_playroomKit.MyPlayer().GetProfile().name} is host?: {isHost}"; } - + /// /// First Click the WaitForState button, then set the color using the dropdown and pressing the SetState button /// @@ -298,7 +304,7 @@ public void WaitForState() { Debug.Log($"data from WaitForPlayer state, color: {data}"); - logsText.text += "\nData from WaitForPlayer state, color: {data}"; + logsText.text += $"\nData from WaitForPlayer state, color: {data}"; }); } @@ -320,4 +326,14 @@ public void ResetPlayerStates() } }); } + + public void GlobalSetState() + { + _playroomKit.SetState("winner", "ChickenGamer"); + } + + public void GlobalGetState() + { + logsText.text = $"getting global (state): Winner is : {_playroomKit.GetState("winner")}"; + } } \ No newline at end of file diff --git a/Assets/PlayroomKit/Examples/package-showcase/showcase.unity b/Assets/PlayroomKit/Examples/package-showcase/showcase.unity index b8f56f6..5f92a3f 100644 --- a/Assets/PlayroomKit/Examples/package-showcase/showcase.unity +++ b/Assets/PlayroomKit/Examples/package-showcase/showcase.unity @@ -98,7 +98,7 @@ LightmapSettings: m_TrainingDataDestination: TrainingData m_LightProbeSampleCountMultiplier: 4 m_LightingDataAsset: {fileID: 0} - m_LightingSettings: {fileID: 0} + m_LightingSettings: {fileID: 309510584} --- !u!196 &4 NavMeshSettings: serializedVersion: 2 @@ -293,7 +293,7 @@ RectTransform: m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} m_AnchorMin: {x: 0.5, y: 0.5} m_AnchorMax: {x: 0.5, y: 0.5} - m_AnchoredPosition: {x: -116, y: 56} + m_AnchoredPosition: {x: -116, y: 14} m_SizeDelta: {x: 210, y: 54.7824} m_Pivot: {x: 0.5, y: 0.5} --- !u!114 &51902008 @@ -596,6 +596,139 @@ CanvasRenderer: m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 90288734} m_CullTransparentMesh: 1 +--- !u!1 &101303170 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 101303171} + - component: {fileID: 101303174} + - component: {fileID: 101303173} + - component: {fileID: 101303172} + m_Layer: 5 + m_Name: SetWinner + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &101303171 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 101303170} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_ConstrainProportionsScale: 0 + m_Children: + - {fileID: 1365511641} + m_Father: {fileID: 345391364} + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0.5, y: 0.5} + m_AnchorMax: {x: 0.5, y: 0.5} + m_AnchoredPosition: {x: -100, y: -36} + m_SizeDelta: {x: 150, y: 55} + m_Pivot: {x: 0.5, y: 0.5} +--- !u!114 &101303172 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 101303170} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 4e29b1a8efbd4b44bb3f3716e73f07ff, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Navigation: + m_Mode: 3 + m_WrapAround: 0 + m_SelectOnUp: {fileID: 0} + m_SelectOnDown: {fileID: 0} + m_SelectOnLeft: {fileID: 0} + m_SelectOnRight: {fileID: 0} + m_Transition: 1 + m_Colors: + m_NormalColor: {r: 1, g: 1, b: 1, a: 1} + m_HighlightedColor: {r: 0.9607843, g: 0.9607843, b: 0.9607843, a: 1} + m_PressedColor: {r: 0.78431374, g: 0.78431374, b: 0.78431374, a: 1} + m_SelectedColor: {r: 0.9607843, g: 0.9607843, b: 0.9607843, a: 1} + m_DisabledColor: {r: 0.78431374, g: 0.78431374, b: 0.78431374, a: 0.5019608} + m_ColorMultiplier: 1 + m_FadeDuration: 0.1 + m_SpriteState: + m_HighlightedSprite: {fileID: 0} + m_PressedSprite: {fileID: 0} + m_SelectedSprite: {fileID: 0} + m_DisabledSprite: {fileID: 0} + m_AnimationTriggers: + m_NormalTrigger: Normal + m_HighlightedTrigger: Highlighted + m_PressedTrigger: Pressed + m_SelectedTrigger: Selected + m_DisabledTrigger: Disabled + m_Interactable: 1 + m_TargetGraphic: {fileID: 1492918781} + m_OnClick: + m_PersistentCalls: + m_Calls: + - m_Target: {fileID: 893908563} + m_TargetAssemblyTypeName: GameManagerDemo, Playroom + m_MethodName: GlobalSetState + m_Mode: 1 + m_Arguments: + m_ObjectArgument: {fileID: 0} + m_ObjectArgumentAssemblyTypeName: UnityEngine.Object, UnityEngine + m_IntArgument: 0 + m_FloatArgument: 0 + m_StringArgument: + m_BoolArgument: 0 + m_CallState: 2 +--- !u!114 &101303173 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 101303170} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: fe87c0e1cc204ed48ad3b37840f39efc, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 1, g: 1, b: 1, a: 1} + m_RaycastTarget: 1 + m_RaycastPadding: {x: 0, y: 0, z: 0, w: 0} + m_Maskable: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_Sprite: {fileID: 10905, guid: 0000000000000000f000000000000000, type: 0} + m_Type: 1 + m_PreserveAspect: 0 + m_FillCenter: 1 + m_FillMethod: 4 + m_FillAmount: 1 + m_FillClockwise: 1 + m_FillOrigin: 0 + m_UseSpriteMesh: 0 + m_PixelsPerUnitMultiplier: 1 +--- !u!222 &101303174 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 101303170} + m_CullTransparentMesh: 1 --- !u!1 &113419432 GameObject: m_ObjectHideFlags: 0 @@ -920,6 +1053,70 @@ CanvasRenderer: m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 223862827} m_CullTransparentMesh: 1 +--- !u!850595691 &309510584 +LightingSettings: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_Name: + serializedVersion: 6 + m_GIWorkflowMode: 1 + m_EnableBakedLightmaps: 1 + m_EnableRealtimeLightmaps: 0 + m_RealtimeEnvironmentLighting: 1 + m_BounceScale: 1 + m_AlbedoBoost: 1 + m_IndirectOutputScale: 1 + m_UsingShadowmask: 1 + m_BakeBackend: 1 + m_LightmapMaxSize: 1024 + m_BakeResolution: 40 + m_Padding: 2 + m_LightmapCompression: 3 + m_AO: 0 + m_AOMaxDistance: 1 + m_CompAOExponent: 1 + m_CompAOExponentDirect: 0 + m_ExtractAO: 0 + m_MixedBakeMode: 2 + m_LightmapsBakeMode: 1 + m_FilterMode: 1 + m_LightmapParameters: {fileID: 15204, guid: 0000000000000000f000000000000000, type: 0} + m_ExportTrainingData: 0 + m_TrainingDataDestination: TrainingData + m_RealtimeResolution: 2 + m_ForceWhiteAlbedo: 0 + m_ForceUpdates: 0 + m_FinalGather: 0 + m_FinalGatherRayCount: 256 + m_FinalGatherFiltering: 1 + m_PVRCulling: 1 + m_PVRSampling: 1 + m_PVRDirectSampleCount: 32 + m_PVRSampleCount: 512 + m_PVREnvironmentSampleCount: 256 + m_PVREnvironmentReferencePointCount: 2048 + m_LightProbeSampleCountMultiplier: 4 + m_PVRBounces: 2 + m_PVRMinBounces: 2 + m_PVREnvironmentImportanceSampling: 1 + m_PVRFilteringMode: 1 + m_PVRDenoiserTypeDirect: 1 + m_PVRDenoiserTypeIndirect: 1 + m_PVRDenoiserTypeAO: 1 + m_PVRFilterTypeDirect: 0 + m_PVRFilterTypeIndirect: 0 + m_PVRFilterTypeAO: 0 + m_PVRFilteringGaussRadiusDirect: 1 + m_PVRFilteringGaussRadiusIndirect: 5 + m_PVRFilteringGaussRadiusAO: 2 + m_PVRFilteringAtrousPositionSigmaDirect: 0.5 + m_PVRFilteringAtrousPositionSigmaIndirect: 2 + m_PVRFilteringAtrousPositionSigmaAO: 1 + m_PVRTiledBaking: 0 + m_NumRaysToShootPerTexel: -1 + m_RespectSceneVisibilityWhenBakingGI: 0 --- !u!1 &330092343 GameObject: m_ObjectHideFlags: 0 @@ -1054,6 +1251,84 @@ CanvasRenderer: m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 330092343} m_CullTransparentMesh: 1 +--- !u!1 &345391363 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 345391364} + - component: {fileID: 345391366} + - component: {fileID: 345391365} + m_Layer: 5 + m_Name: Global States Panel + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &345391364 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 345391363} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_ConstrainProportionsScale: 0 + m_Children: + - {fileID: 1069799746} + - {fileID: 101303171} + - {fileID: 716188108} + m_Father: {fileID: 1643951926} + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 1, y: 0} + m_AnchorMax: {x: 1, y: 1} + m_AnchoredPosition: {x: 0, y: 89.55347} + m_SizeDelta: {x: 500, y: -843.3069} + m_Pivot: {x: 1, y: 0.5} +--- !u!114 &345391365 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 345391363} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: fe87c0e1cc204ed48ad3b37840f39efc, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 0.23529413, g: 0.23529413, b: 0.23529413, a: 0.8} + m_RaycastTarget: 1 + m_RaycastPadding: {x: 0, y: 0, z: 0, w: 0} + m_Maskable: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_Sprite: {fileID: 10907, guid: 0000000000000000f000000000000000, type: 0} + m_Type: 1 + m_PreserveAspect: 0 + m_FillCenter: 1 + m_FillMethod: 4 + m_FillAmount: 1 + m_FillClockwise: 1 + m_FillOrigin: 0 + m_UseSpriteMesh: 0 + m_PixelsPerUnitMultiplier: 1 +--- !u!222 &345391366 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 345391363} + m_CullTransparentMesh: 1 --- !u!1 &350738682 GameObject: m_ObjectHideFlags: 0 @@ -2152,7 +2427,7 @@ CanvasRenderer: m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 706413132} m_CullTransparentMesh: 1 ---- !u!1 &733515443 +--- !u!1 &716188107 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} @@ -2160,57 +2435,190 @@ GameObject: m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - - component: {fileID: 733515444} - - component: {fileID: 733515446} - - component: {fileID: 733515445} + - component: {fileID: 716188108} + - component: {fileID: 716188111} + - component: {fileID: 716188110} + - component: {fileID: 716188109} m_Layer: 5 - m_Name: Item Background + m_Name: GetWinner m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 ---- !u!224 &733515444 +--- !u!224 &716188108 RectTransform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} - m_GameObject: {fileID: 733515443} - m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_GameObject: {fileID: 716188107} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} m_ConstrainProportionsScale: 0 - m_Children: [] - m_Father: {fileID: 1269959009} + m_Children: + - {fileID: 1492918780} + m_Father: {fileID: 345391364} m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} - m_AnchorMin: {x: 0, y: 0} - m_AnchorMax: {x: 1, y: 1} - m_AnchoredPosition: {x: 0, y: 0} - m_SizeDelta: {x: 0, y: 0} + m_AnchorMin: {x: 0.5, y: 0.5} + m_AnchorMax: {x: 0.5, y: 0.5} + m_AnchoredPosition: {x: 100, y: -36} + m_SizeDelta: {x: 150, y: 55} m_Pivot: {x: 0.5, y: 0.5} ---- !u!114 &733515445 +--- !u!114 &716188109 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} - m_GameObject: {fileID: 733515443} + m_GameObject: {fileID: 716188107} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 4e29b1a8efbd4b44bb3f3716e73f07ff, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Navigation: + m_Mode: 3 + m_WrapAround: 0 + m_SelectOnUp: {fileID: 0} + m_SelectOnDown: {fileID: 0} + m_SelectOnLeft: {fileID: 0} + m_SelectOnRight: {fileID: 0} + m_Transition: 1 + m_Colors: + m_NormalColor: {r: 1, g: 1, b: 1, a: 1} + m_HighlightedColor: {r: 0.9607843, g: 0.9607843, b: 0.9607843, a: 1} + m_PressedColor: {r: 0.78431374, g: 0.78431374, b: 0.78431374, a: 1} + m_SelectedColor: {r: 0.9607843, g: 0.9607843, b: 0.9607843, a: 1} + m_DisabledColor: {r: 0.78431374, g: 0.78431374, b: 0.78431374, a: 0.5019608} + m_ColorMultiplier: 1 + m_FadeDuration: 0.1 + m_SpriteState: + m_HighlightedSprite: {fileID: 0} + m_PressedSprite: {fileID: 0} + m_SelectedSprite: {fileID: 0} + m_DisabledSprite: {fileID: 0} + m_AnimationTriggers: + m_NormalTrigger: Normal + m_HighlightedTrigger: Highlighted + m_PressedTrigger: Pressed + m_SelectedTrigger: Selected + m_DisabledTrigger: Disabled + m_Interactable: 1 + m_TargetGraphic: {fileID: 1492918781} + m_OnClick: + m_PersistentCalls: + m_Calls: + - m_Target: {fileID: 893908563} + m_TargetAssemblyTypeName: GameManagerDemo, Playroom + m_MethodName: GlobalGetState + m_Mode: 1 + m_Arguments: + m_ObjectArgument: {fileID: 0} + m_ObjectArgumentAssemblyTypeName: UnityEngine.Object, UnityEngine + m_IntArgument: 0 + m_FloatArgument: 0 + m_StringArgument: + m_BoolArgument: 0 + m_CallState: 1 +--- !u!114 &716188110 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 716188107} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: fe87c0e1cc204ed48ad3b37840f39efc, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} - m_Color: {r: 0.9607843, g: 0.9607843, b: 0.9607843, a: 1} + m_Color: {r: 1, g: 1, b: 1, a: 1} m_RaycastTarget: 1 m_RaycastPadding: {x: 0, y: 0, z: 0, w: 0} m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] - m_Sprite: {fileID: 0} - m_Type: 0 + m_Sprite: {fileID: 10905, guid: 0000000000000000f000000000000000, type: 0} + m_Type: 1 + m_PreserveAspect: 0 + m_FillCenter: 1 + m_FillMethod: 4 + m_FillAmount: 1 + m_FillClockwise: 1 + m_FillOrigin: 0 + m_UseSpriteMesh: 0 + m_PixelsPerUnitMultiplier: 1 +--- !u!222 &716188111 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 716188107} + m_CullTransparentMesh: 1 +--- !u!1 &733515443 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 733515444} + - component: {fileID: 733515446} + - component: {fileID: 733515445} + m_Layer: 5 + m_Name: Item Background + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &733515444 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 733515443} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_ConstrainProportionsScale: 0 + m_Children: [] + m_Father: {fileID: 1269959009} + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 0} + m_AnchorMax: {x: 1, y: 1} + m_AnchoredPosition: {x: 0, y: 0} + m_SizeDelta: {x: 0, y: 0} + m_Pivot: {x: 0.5, y: 0.5} +--- !u!114 &733515445 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 733515443} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: fe87c0e1cc204ed48ad3b37840f39efc, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 0.9607843, g: 0.9607843, b: 0.9607843, a: 1} + m_RaycastTarget: 1 + m_RaycastPadding: {x: 0, y: 0, z: 0, w: 0} + m_Maskable: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_Sprite: {fileID: 0} + m_Type: 0 m_PreserveAspect: 0 m_FillCenter: 1 m_FillMethod: 4 @@ -2399,7 +2807,7 @@ RectTransform: m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} m_AnchorMin: {x: 0.5, y: 0.5} m_AnchorMax: {x: 0.5, y: 0.5} - m_AnchoredPosition: {x: -116, y: -43} + m_AnchoredPosition: {x: -116, y: -85} m_SizeDelta: {x: 210, y: 60} m_Pivot: {x: 0.5, y: 0.5} --- !u!114 &738191203 @@ -2534,7 +2942,7 @@ RectTransform: m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} m_AnchorMin: {x: 0.5, y: 0.5} m_AnchorMax: {x: 0.5, y: 0.5} - m_AnchoredPosition: {x: 128.01, y: -34.3} + m_AnchoredPosition: {x: 128.01, y: -76.3} m_SizeDelta: {x: 188.08, y: 60} m_Pivot: {x: 0.5, y: 0.5} --- !u!114 &778435531 @@ -2871,7 +3279,7 @@ RectTransform: m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} m_AnchorMin: {x: 0.5, y: 0.5} m_AnchorMax: {x: 0.5, y: 0.5} - m_AnchoredPosition: {x: 128, y: 42} + m_AnchoredPosition: {x: 128, y: 0} m_SizeDelta: {x: 188.0993, y: 60} m_Pivot: {x: 0.5, y: 0.5} --- !u!114 &916618229 @@ -2996,7 +3404,7 @@ GameObject: - component: {fileID: 928895525} - component: {fileID: 928895524} m_Layer: 5 - m_Name: SetGetPanel + m_Name: PlayerSetGetPanel m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 @@ -3014,6 +3422,7 @@ RectTransform: m_LocalScale: {x: 1, y: 1, z: 1} m_ConstrainProportionsScale: 0 m_Children: + - {fileID: 1701676165} - {fileID: 916618228} - {fileID: 51902007} - {fileID: 738191202} @@ -3022,8 +3431,8 @@ RectTransform: m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} m_AnchorMin: {x: 1, y: 0} m_AnchorMax: {x: 1, y: 1} - m_AnchoredPosition: {x: 0, y: 435.0025} - m_SizeDelta: {x: 500, y: -869.995} + m_AnchoredPosition: {x: 0, y: 387.67252} + m_SizeDelta: {x: 500, y: -775.335} m_Pivot: {x: 1, y: 0.5} --- !u!114 &928895524 MonoBehaviour: @@ -3532,6 +3941,140 @@ BoxCollider: serializedVersion: 3 m_Size: {x: 1, y: 1, z: 1} m_Center: {x: 0, y: 0, z: 0} +--- !u!1 &1069799745 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1069799746} + - component: {fileID: 1069799748} + - component: {fileID: 1069799747} + m_Layer: 5 + m_Name: Text (TMP) + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &1069799746 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1069799745} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_ConstrainProportionsScale: 0 + m_Children: [] + m_Father: {fileID: 345391364} + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 0.5} + m_AnchorMax: {x: 1, y: 0.5} + m_AnchoredPosition: {x: 0, y: 68} + m_SizeDelta: {x: 0, y: 50} + m_Pivot: {x: 0.5, y: 0.5} +--- !u!114 &1069799747 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1069799745} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: f4688fdb7df04437aeb418b961361dc5, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 1, g: 1, b: 1, a: 1} + m_RaycastTarget: 1 + m_RaycastPadding: {x: 0, y: 0, z: 0, w: 0} + m_Maskable: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_text: Game / Global States + m_isRightToLeft: 0 + m_fontAsset: {fileID: 11400000, guid: 8f586378b4e144a9851e7b34d9b748ee, type: 2} + m_sharedMaterial: {fileID: 2180264, guid: 8f586378b4e144a9851e7b34d9b748ee, type: 2} + m_fontSharedMaterials: [] + m_fontMaterial: {fileID: 0} + m_fontMaterials: [] + m_fontColor32: + serializedVersion: 2 + rgba: 4294967295 + m_fontColor: {r: 1, g: 1, b: 1, a: 1} + m_enableVertexGradient: 0 + m_colorMode: 3 + m_fontColorGradient: + topLeft: {r: 1, g: 1, b: 1, a: 1} + topRight: {r: 1, g: 1, b: 1, a: 1} + bottomLeft: {r: 1, g: 1, b: 1, a: 1} + bottomRight: {r: 1, g: 1, b: 1, a: 1} + m_fontColorGradientPreset: {fileID: 0} + m_spriteAsset: {fileID: 0} + m_tintAllSprites: 0 + m_StyleSheet: {fileID: 0} + m_TextStyleHashCode: -1183493901 + m_overrideHtmlColors: 0 + m_faceColor: + serializedVersion: 2 + rgba: 4294967295 + m_fontSize: 44.75 + m_fontSizeBase: 36 + m_fontWeight: 400 + m_enableAutoSizing: 1 + m_fontSizeMin: 18 + m_fontSizeMax: 72 + m_fontStyle: 4 + m_HorizontalAlignment: 2 + m_VerticalAlignment: 512 + m_textAlignment: 65535 + m_characterSpacing: 0 + m_wordSpacing: 0 + m_lineSpacing: 0 + m_lineSpacingMax: 0 + m_paragraphSpacing: 0 + m_charWidthMaxAdj: 0 + m_enableWordWrapping: 1 + m_wordWrappingRatios: 0.4 + m_overflowMode: 0 + m_linkedTextComponent: {fileID: 0} + parentLinkedComponent: {fileID: 0} + m_enableKerning: 1 + m_enableExtraPadding: 0 + checkPaddingRequired: 0 + m_isRichText: 1 + m_parseCtrlCharacters: 1 + m_isOrthographic: 1 + m_isCullingEnabled: 0 + m_horizontalMapping: 0 + m_verticalMapping: 0 + m_uvLineOffset: 0 + m_geometrySortingOrder: 0 + m_IsTextObjectScaleStatic: 0 + m_VertexBufferAutoSizeReduction: 0 + m_useMaxVisibleDescender: 1 + m_pageToDisplay: 1 + m_margin: {x: 0, y: 0, z: 0, w: 0} + m_isUsingLegacyAnimationComponent: 0 + m_isVolumetricText: 0 + m_hasFontAssetChanged: 0 + m_baseMaterial: {fileID: 0} + m_maskOffset: {x: 0, y: 0, z: 0, w: 0} +--- !u!222 &1069799748 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1069799745} + m_CullTransparentMesh: 1 --- !u!1 &1083690561 GameObject: m_ObjectHideFlags: 0 @@ -4289,6 +4832,142 @@ CanvasRenderer: m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1337452018} m_CullTransparentMesh: 1 +--- !u!1 &1365511640 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1365511641} + - component: {fileID: 1365511643} + - component: {fileID: 1365511642} + m_Layer: 5 + m_Name: Text (TMP) + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &1365511641 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1365511640} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_ConstrainProportionsScale: 0 + m_Children: [] + m_Father: {fileID: 101303171} + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 0} + m_AnchorMax: {x: 1, y: 1} + m_AnchoredPosition: {x: 0, y: 0} + m_SizeDelta: {x: 0, y: 0} + m_Pivot: {x: 0.5, y: 0.5} +--- !u!114 &1365511642 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1365511640} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: f4688fdb7df04437aeb418b961361dc5, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 1, g: 1, b: 1, a: 1} + m_RaycastTarget: 1 + m_RaycastPadding: {x: 0, y: 0, z: 0, w: 0} + m_Maskable: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_text: 'SetState + +' + m_isRightToLeft: 0 + m_fontAsset: {fileID: 11400000, guid: 8f586378b4e144a9851e7b34d9b748ee, type: 2} + m_sharedMaterial: {fileID: 2180264, guid: 8f586378b4e144a9851e7b34d9b748ee, type: 2} + m_fontSharedMaterials: [] + m_fontMaterial: {fileID: 0} + m_fontMaterials: [] + m_fontColor32: + serializedVersion: 2 + rgba: 4281479730 + m_fontColor: {r: 0.19607843, g: 0.19607843, b: 0.19607843, a: 1} + m_enableVertexGradient: 0 + m_colorMode: 3 + m_fontColorGradient: + topLeft: {r: 1, g: 1, b: 1, a: 1} + topRight: {r: 1, g: 1, b: 1, a: 1} + bottomLeft: {r: 1, g: 1, b: 1, a: 1} + bottomRight: {r: 1, g: 1, b: 1, a: 1} + m_fontColorGradientPreset: {fileID: 0} + m_spriteAsset: {fileID: 0} + m_tintAllSprites: 0 + m_StyleSheet: {fileID: 0} + m_TextStyleHashCode: -1183493901 + m_overrideHtmlColors: 0 + m_faceColor: + serializedVersion: 2 + rgba: 4294967295 + m_fontSize: 24 + m_fontSizeBase: 24 + m_fontWeight: 400 + m_enableAutoSizing: 0 + m_fontSizeMin: 18 + m_fontSizeMax: 72 + m_fontStyle: 0 + m_HorizontalAlignment: 2 + m_VerticalAlignment: 512 + m_textAlignment: 65535 + m_characterSpacing: 0 + m_wordSpacing: 0 + m_lineSpacing: 0 + m_lineSpacingMax: 0 + m_paragraphSpacing: 0 + m_charWidthMaxAdj: 0 + m_enableWordWrapping: 1 + m_wordWrappingRatios: 0.4 + m_overflowMode: 0 + m_linkedTextComponent: {fileID: 0} + parentLinkedComponent: {fileID: 0} + m_enableKerning: 1 + m_enableExtraPadding: 0 + checkPaddingRequired: 0 + m_isRichText: 1 + m_parseCtrlCharacters: 1 + m_isOrthographic: 1 + m_isCullingEnabled: 0 + m_horizontalMapping: 0 + m_verticalMapping: 0 + m_uvLineOffset: 0 + m_geometrySortingOrder: 0 + m_IsTextObjectScaleStatic: 0 + m_VertexBufferAutoSizeReduction: 0 + m_useMaxVisibleDescender: 1 + m_pageToDisplay: 1 + m_margin: {x: 0, y: 0, z: 0, w: 1.4778595} + m_isUsingLegacyAnimationComponent: 0 + m_isVolumetricText: 0 + m_hasFontAssetChanged: 0 + m_baseMaterial: {fileID: 0} + m_maskOffset: {x: 0, y: 0, z: 0, w: 0} +--- !u!222 &1365511643 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1365511640} + m_CullTransparentMesh: 1 --- !u!1 &1366794680 GameObject: m_ObjectHideFlags: 0 @@ -4655,9 +5334,145 @@ GameObject: m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - - component: {fileID: 1451208486} - - component: {fileID: 1451208488} - - component: {fileID: 1451208487} + - component: {fileID: 1451208486} + - component: {fileID: 1451208488} + - component: {fileID: 1451208487} + m_Layer: 5 + m_Name: Text (TMP) + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &1451208486 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1451208485} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_ConstrainProportionsScale: 0 + m_Children: [] + m_Father: {fileID: 949231289} + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 0} + m_AnchorMax: {x: 1, y: 1} + m_AnchoredPosition: {x: 0, y: 0} + m_SizeDelta: {x: 0, y: 0} + m_Pivot: {x: 0.5, y: 0.5} +--- !u!114 &1451208487 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1451208485} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: f4688fdb7df04437aeb418b961361dc5, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 1, g: 1, b: 1, a: 1} + m_RaycastTarget: 1 + m_RaycastPadding: {x: 0, y: 0, z: 0, w: 0} + m_Maskable: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_text: 'InsertCoin + +' + m_isRightToLeft: 0 + m_fontAsset: {fileID: 11400000, guid: 8f586378b4e144a9851e7b34d9b748ee, type: 2} + m_sharedMaterial: {fileID: 2180264, guid: 8f586378b4e144a9851e7b34d9b748ee, type: 2} + m_fontSharedMaterials: [] + m_fontMaterial: {fileID: 0} + m_fontMaterials: [] + m_fontColor32: + serializedVersion: 2 + rgba: 4281479730 + m_fontColor: {r: 0.19607843, g: 0.19607843, b: 0.19607843, a: 1} + m_enableVertexGradient: 0 + m_colorMode: 3 + m_fontColorGradient: + topLeft: {r: 1, g: 1, b: 1, a: 1} + topRight: {r: 1, g: 1, b: 1, a: 1} + bottomLeft: {r: 1, g: 1, b: 1, a: 1} + bottomRight: {r: 1, g: 1, b: 1, a: 1} + m_fontColorGradientPreset: {fileID: 0} + m_spriteAsset: {fileID: 0} + m_tintAllSprites: 0 + m_StyleSheet: {fileID: 0} + m_TextStyleHashCode: -1183493901 + m_overrideHtmlColors: 0 + m_faceColor: + serializedVersion: 2 + rgba: 4294967295 + m_fontSize: 24 + m_fontSizeBase: 24 + m_fontWeight: 400 + m_enableAutoSizing: 0 + m_fontSizeMin: 18 + m_fontSizeMax: 72 + m_fontStyle: 0 + m_HorizontalAlignment: 2 + m_VerticalAlignment: 512 + m_textAlignment: 65535 + m_characterSpacing: 0 + m_wordSpacing: 0 + m_lineSpacing: 0 + m_lineSpacingMax: 0 + m_paragraphSpacing: 0 + m_charWidthMaxAdj: 0 + m_enableWordWrapping: 1 + m_wordWrappingRatios: 0.4 + m_overflowMode: 0 + m_linkedTextComponent: {fileID: 0} + parentLinkedComponent: {fileID: 0} + m_enableKerning: 1 + m_enableExtraPadding: 0 + checkPaddingRequired: 0 + m_isRichText: 1 + m_parseCtrlCharacters: 1 + m_isOrthographic: 1 + m_isCullingEnabled: 0 + m_horizontalMapping: 0 + m_verticalMapping: 0 + m_uvLineOffset: 0 + m_geometrySortingOrder: 0 + m_IsTextObjectScaleStatic: 0 + m_VertexBufferAutoSizeReduction: 0 + m_useMaxVisibleDescender: 1 + m_pageToDisplay: 1 + m_margin: {x: 0, y: 0, z: 0, w: 0} + m_isUsingLegacyAnimationComponent: 0 + m_isVolumetricText: 0 + m_hasFontAssetChanged: 0 + m_baseMaterial: {fileID: 0} + m_maskOffset: {x: 0, y: 0, z: 0, w: 0} +--- !u!222 &1451208488 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1451208485} + m_CullTransparentMesh: 1 +--- !u!1 &1492918779 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1492918780} + - component: {fileID: 1492918782} + - component: {fileID: 1492918781} m_Layer: 5 m_Name: Text (TMP) m_TagString: Untagged @@ -4665,32 +5480,32 @@ GameObject: m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 ---- !u!224 &1451208486 +--- !u!224 &1492918780 RectTransform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} - m_GameObject: {fileID: 1451208485} + m_GameObject: {fileID: 1492918779} m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} m_ConstrainProportionsScale: 0 m_Children: [] - m_Father: {fileID: 949231289} + m_Father: {fileID: 716188108} m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} m_AnchorMin: {x: 0, y: 0} m_AnchorMax: {x: 1, y: 1} m_AnchoredPosition: {x: 0, y: 0} m_SizeDelta: {x: 0, y: 0} m_Pivot: {x: 0.5, y: 0.5} ---- !u!114 &1451208487 +--- !u!114 &1492918781 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} - m_GameObject: {fileID: 1451208485} + m_GameObject: {fileID: 1492918779} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: f4688fdb7df04437aeb418b961361dc5, type: 3} @@ -4704,9 +5519,7 @@ MonoBehaviour: m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] - m_text: 'InsertCoin - -' + m_text: GetState m_isRightToLeft: 0 m_fontAsset: {fileID: 11400000, guid: 8f586378b4e144a9851e7b34d9b748ee, type: 2} m_sharedMaterial: {fileID: 2180264, guid: 8f586378b4e144a9851e7b34d9b748ee, type: 2} @@ -4775,13 +5588,13 @@ MonoBehaviour: m_hasFontAssetChanged: 0 m_baseMaterial: {fileID: 0} m_maskOffset: {x: 0, y: 0, z: 0, w: 0} ---- !u!222 &1451208488 +--- !u!222 &1492918782 CanvasRenderer: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} - m_GameObject: {fileID: 1451208485} + m_GameObject: {fileID: 1492918779} m_CullTransparentMesh: 1 --- !u!1 &1516353994 GameObject: @@ -5509,6 +6322,7 @@ RectTransform: m_Children: - {fileID: 1123907210} - {fileID: 928895523} + - {fileID: 345391364} - {fileID: 1956131791} - {fileID: 90288735} - {fileID: 1883683082} @@ -5555,6 +6369,140 @@ RectTransform: m_AnchoredPosition: {x: 0, y: 0} m_SizeDelta: {x: 0, y: 28} m_Pivot: {x: 0.5, y: 1} +--- !u!1 &1701676164 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1701676165} + - component: {fileID: 1701676167} + - component: {fileID: 1701676166} + m_Layer: 5 + m_Name: Text (TMP) + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &1701676165 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1701676164} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_ConstrainProportionsScale: 0 + m_Children: [] + m_Father: {fileID: 928895523} + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 0.5} + m_AnchorMax: {x: 1, y: 0.5} + m_AnchoredPosition: {x: 0, y: 113} + m_SizeDelta: {x: 0, y: 50} + m_Pivot: {x: 0.5, y: 0.5} +--- !u!114 &1701676166 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1701676164} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: f4688fdb7df04437aeb418b961361dc5, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 1, g: 1, b: 1, a: 1} + m_RaycastTarget: 1 + m_RaycastPadding: {x: 0, y: 0, z: 0, w: 0} + m_Maskable: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_text: Player States + m_isRightToLeft: 0 + m_fontAsset: {fileID: 11400000, guid: 8f586378b4e144a9851e7b34d9b748ee, type: 2} + m_sharedMaterial: {fileID: 2180264, guid: 8f586378b4e144a9851e7b34d9b748ee, type: 2} + m_fontSharedMaterials: [] + m_fontMaterial: {fileID: 0} + m_fontMaterials: [] + m_fontColor32: + serializedVersion: 2 + rgba: 4294967295 + m_fontColor: {r: 1, g: 1, b: 1, a: 1} + m_enableVertexGradient: 0 + m_colorMode: 3 + m_fontColorGradient: + topLeft: {r: 1, g: 1, b: 1, a: 1} + topRight: {r: 1, g: 1, b: 1, a: 1} + bottomLeft: {r: 1, g: 1, b: 1, a: 1} + bottomRight: {r: 1, g: 1, b: 1, a: 1} + m_fontColorGradientPreset: {fileID: 0} + m_spriteAsset: {fileID: 0} + m_tintAllSprites: 0 + m_StyleSheet: {fileID: 0} + m_TextStyleHashCode: -1183493901 + m_overrideHtmlColors: 0 + m_faceColor: + serializedVersion: 2 + rgba: 4294967295 + m_fontSize: 44.75 + m_fontSizeBase: 36 + m_fontWeight: 400 + m_enableAutoSizing: 1 + m_fontSizeMin: 18 + m_fontSizeMax: 72 + m_fontStyle: 4 + m_HorizontalAlignment: 2 + m_VerticalAlignment: 512 + m_textAlignment: 65535 + m_characterSpacing: 0 + m_wordSpacing: 0 + m_lineSpacing: 0 + m_lineSpacingMax: 0 + m_paragraphSpacing: 0 + m_charWidthMaxAdj: 0 + m_enableWordWrapping: 1 + m_wordWrappingRatios: 0.4 + m_overflowMode: 0 + m_linkedTextComponent: {fileID: 0} + parentLinkedComponent: {fileID: 0} + m_enableKerning: 1 + m_enableExtraPadding: 0 + checkPaddingRequired: 0 + m_isRichText: 1 + m_parseCtrlCharacters: 1 + m_isOrthographic: 1 + m_isCullingEnabled: 0 + m_horizontalMapping: 0 + m_verticalMapping: 0 + m_uvLineOffset: 0 + m_geometrySortingOrder: 0 + m_IsTextObjectScaleStatic: 0 + m_VertexBufferAutoSizeReduction: 0 + m_useMaxVisibleDescender: 1 + m_pageToDisplay: 1 + m_margin: {x: 0, y: 0, z: 0, w: 0} + m_isUsingLegacyAnimationComponent: 0 + m_isVolumetricText: 0 + m_hasFontAssetChanged: 0 + m_baseMaterial: {fileID: 0} + m_maskOffset: {x: 0, y: 0, z: 0, w: 0} +--- !u!222 &1701676167 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1701676164} + m_CullTransparentMesh: 1 --- !u!1 &1747618314 GameObject: m_ObjectHideFlags: 0 @@ -5823,94 +6771,6 @@ CanvasRenderer: m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1826344565} m_CullTransparentMesh: 1 ---- !u!1001 &1851333564 -PrefabInstance: - m_ObjectHideFlags: 0 - serializedVersion: 2 - m_Modification: - serializedVersion: 3 - m_TransformParent: {fileID: 0} - m_Modifications: - - target: {fileID: 1957495583081457048, guid: 1b30fa3a265114a45a7e23165a20aecc, type: 3} - propertyPath: m_Name - value: PlayroomMockManager - objectReference: {fileID: 0} - - target: {fileID: 3746181030263044757, guid: 1b30fa3a265114a45a7e23165a20aecc, type: 3} - propertyPath: m_LocalPosition.x - value: -0.3 - objectReference: {fileID: 0} - - target: {fileID: 3746181030263044757, guid: 1b30fa3a265114a45a7e23165a20aecc, type: 3} - propertyPath: m_LocalPosition.y - value: 0 - objectReference: {fileID: 0} - - target: {fileID: 3746181030263044757, guid: 1b30fa3a265114a45a7e23165a20aecc, type: 3} - propertyPath: m_LocalPosition.z - value: 0 - objectReference: {fileID: 0} - - target: {fileID: 3746181030263044757, guid: 1b30fa3a265114a45a7e23165a20aecc, type: 3} - propertyPath: m_LocalRotation.w - value: 1 - objectReference: {fileID: 0} - - target: {fileID: 3746181030263044757, guid: 1b30fa3a265114a45a7e23165a20aecc, type: 3} - propertyPath: m_LocalRotation.x - value: 0 - objectReference: {fileID: 0} - - target: {fileID: 3746181030263044757, guid: 1b30fa3a265114a45a7e23165a20aecc, type: 3} - propertyPath: m_LocalRotation.y - value: 0 - objectReference: {fileID: 0} - - target: {fileID: 3746181030263044757, guid: 1b30fa3a265114a45a7e23165a20aecc, type: 3} - propertyPath: m_LocalRotation.z - value: 0 - objectReference: {fileID: 0} - - target: {fileID: 3746181030263044757, guid: 1b30fa3a265114a45a7e23165a20aecc, type: 3} - propertyPath: m_LocalEulerAnglesHint.x - value: 0 - objectReference: {fileID: 0} - - target: {fileID: 3746181030263044757, guid: 1b30fa3a265114a45a7e23165a20aecc, type: 3} - propertyPath: m_LocalEulerAnglesHint.y - value: 0 - objectReference: {fileID: 0} - - target: {fileID: 3746181030263044757, guid: 1b30fa3a265114a45a7e23165a20aecc, type: 3} - propertyPath: m_LocalEulerAnglesHint.z - value: 0 - objectReference: {fileID: 0} - - target: {fileID: 5593001685836374760, guid: 1b30fa3a265114a45a7e23165a20aecc, type: 3} - propertyPath: mockMode - value: 0 - objectReference: {fileID: 0} - - target: {fileID: 5593001685836374760, guid: 1b30fa3a265114a45a7e23165a20aecc, type: 3} - propertyPath: insertCoinCaller - value: - objectReference: {fileID: 0} - m_RemovedComponents: - - {fileID: 5593001685836374760, guid: 1b30fa3a265114a45a7e23165a20aecc, type: 3} - m_RemovedGameObjects: [] - m_AddedGameObjects: [] - m_AddedComponents: - - targetCorrespondingSourceObject: {fileID: 1957495583081457048, guid: 1b30fa3a265114a45a7e23165a20aecc, type: 3} - insertIndex: -1 - addedObject: {fileID: 1851333566} - m_SourcePrefab: {fileID: 100100000, guid: 1b30fa3a265114a45a7e23165a20aecc, type: 3} ---- !u!1 &1851333565 stripped -GameObject: - m_CorrespondingSourceObject: {fileID: 1957495583081457048, guid: 1b30fa3a265114a45a7e23165a20aecc, type: 3} - m_PrefabInstance: {fileID: 1851333564} - m_PrefabAsset: {fileID: 0} ---- !u!114 &1851333566 -MonoBehaviour: - m_ObjectHideFlags: 0 - m_CorrespondingSourceObject: {fileID: 0} - m_PrefabInstance: {fileID: 0} - m_PrefabAsset: {fileID: 0} - m_GameObject: {fileID: 1851333565} - m_Enabled: 1 - m_EditorHideFlags: 0 - m_Script: {fileID: 11500000, guid: 120dfa1b0ad7e96479cb0286e61ad19d, type: 3} - m_Name: - m_EditorClassIdentifier: - mockMode: 0 - insertCoinCaller: {fileID: 0} --- !u!1 &1883683081 GameObject: m_ObjectHideFlags: 0 @@ -6855,6 +7715,71 @@ CanvasRenderer: m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 2143370850} m_CullTransparentMesh: 1 +--- !u!1001 &2854658873105489201 +PrefabInstance: + m_ObjectHideFlags: 0 + serializedVersion: 2 + m_Modification: + serializedVersion: 3 + m_TransformParent: {fileID: 0} + m_Modifications: + - target: {fileID: 1824217503633254899, guid: 1b30fa3a265114a45a7e23165a20aecc, type: 3} + propertyPath: m_Name + value: PlayroomMockManager + objectReference: {fileID: 0} + - target: {fileID: 4611920177403363027, guid: 1b30fa3a265114a45a7e23165a20aecc, type: 3} + propertyPath: m_LocalPosition.x + value: -0.3 + objectReference: {fileID: 0} + - target: {fileID: 4611920177403363027, guid: 1b30fa3a265114a45a7e23165a20aecc, type: 3} + propertyPath: m_LocalPosition.y + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 4611920177403363027, guid: 1b30fa3a265114a45a7e23165a20aecc, type: 3} + propertyPath: m_LocalPosition.z + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 4611920177403363027, guid: 1b30fa3a265114a45a7e23165a20aecc, type: 3} + propertyPath: m_LocalRotation.w + value: 1 + objectReference: {fileID: 0} + - target: {fileID: 4611920177403363027, guid: 1b30fa3a265114a45a7e23165a20aecc, type: 3} + propertyPath: m_LocalRotation.x + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 4611920177403363027, guid: 1b30fa3a265114a45a7e23165a20aecc, type: 3} + propertyPath: m_LocalRotation.y + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 4611920177403363027, guid: 1b30fa3a265114a45a7e23165a20aecc, type: 3} + propertyPath: m_LocalRotation.z + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 4611920177403363027, guid: 1b30fa3a265114a45a7e23165a20aecc, type: 3} + propertyPath: m_LocalEulerAnglesHint.x + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 4611920177403363027, guid: 1b30fa3a265114a45a7e23165a20aecc, type: 3} + propertyPath: m_LocalEulerAnglesHint.y + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 4611920177403363027, guid: 1b30fa3a265114a45a7e23165a20aecc, type: 3} + propertyPath: m_LocalEulerAnglesHint.z + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 8899696337967424923, guid: 1b30fa3a265114a45a7e23165a20aecc, type: 3} + propertyPath: webDriverDirectory + value: Assets\ + objectReference: {fileID: 0} + - target: {fileID: 8987662522597341863, guid: 1b30fa3a265114a45a7e23165a20aecc, type: 3} + propertyPath: insertCoinCaller + value: + objectReference: {fileID: 893908560} + m_RemovedComponents: [] + m_RemovedGameObjects: [] + m_AddedGameObjects: [] + m_AddedComponents: [] + m_SourcePrefab: {fileID: 100100000, guid: 1b30fa3a265114a45a7e23165a20aecc, type: 3} --- !u!1660057539 &9223372036854775807 SceneRoots: m_ObjectHideFlags: 0 @@ -6866,4 +7791,4 @@ SceneRoots: - {fileID: 417229588} - {fileID: 1643951926} - {fileID: 181053975} - - {fileID: 1851333564} + - {fileID: 2854658873105489201} diff --git a/Assets/PlayroomKit/PlayroomKit.cs b/Assets/PlayroomKit/PlayroomKit.cs index 9b26738..c9528df 100644 --- a/Assets/PlayroomKit/PlayroomKit.cs +++ b/Assets/PlayroomKit/PlayroomKit.cs @@ -1,70 +1,85 @@ using UnityEngine; using System.Collections.Generic; using System; - - +using UBB; namespace Playroom { public partial class PlayroomKit { - private IPlayroomBase _playroomService; + private readonly IPlayroomBase _playroomService; + private readonly IRPC _rpc; + private static PlayroomKit _instance; - private IRPC _rpc; - public static bool isPlayRoomInitialized; + public static bool IsPlayRoomInitialized; private static readonly Dictionary Players = new(); - - static Action startMatchmakingCallback = null; + public enum MockModeSelector + { + Local, + Browser + } + + public static MockModeSelector CurrentMockMode { get; set; } = MockModeSelector.Local; + + // Constructor public PlayroomKit() { - if (IsRunningInBrowser()) - { - _playroomService = new PlayroomService(new PlayroomKitInterop()); +#if !UNITY_EDITOR + _playroomService = new PlayroomBuildService(new PlayroomKitInterop()); _rpc = new RPC(this); - } - else + +#elif UNITY_EDITOR + + if (CurrentMockMode == MockModeSelector.Local) { _playroomService = new LocalMockPlayroomService(); _rpc = new RPCLocal(); } + else if (CurrentMockMode == MockModeSelector.Browser) + { + _playroomService = new BrowserMockService(); + _rpc = new BrowserMockRPC(); + } +#endif } - - public PlayroomKit(IPlayroomBase playroomService, IRPC rpc) + + public PlayroomKit(IPlayroomBase playroomService, IRPC rpc) { _playroomService = playroomService; _rpc = rpc; } - + public void InsertCoin(InitOptions options = null, Action onLaunchCallBack = null, Action onDisconnectCallback = null) { _playroomService.InsertCoin(options, onLaunchCallBack, onDisconnectCallback); } - + public bool IsHost() { - if (!isPlayRoomInitialized) + if (!IsPlayRoomInitialized) { Debug.LogError("[Mock Mode] Playroom not initialized yet! Please call InsertCoin."); return false; } + return _playroomService.IsHost(); } - - public Action OnPlayerJoin(Action onPlayerJoinCallback) + + public void OnPlayerJoin(Action onPlayerJoinCallback) { - if (!isPlayRoomInitialized) + if (!IsPlayRoomInitialized) { Debug.LogError("PlayroomKit is not loaded!. Please make sure to call InsertCoin first."); - return null; + return; } - return _playroomService.OnPlayerJoin(onPlayerJoinCallback); + _playroomService.OnPlayerJoin(onPlayerJoinCallback); } - - public static Player GetPlayer(string playerId) + + public Player GetPlayer(string playerId) { if (Players.TryGetValue(playerId, out var player)) { @@ -74,7 +89,15 @@ public static Player GetPlayer(string playerId) { if (!IsRunningInBrowser()) { - player = new Player(playerId, new Player.LocalPlayerService(playerId)); + if (CurrentMockMode == MockModeSelector.Local) + { + player = new Player(playerId, new Player.LocalPlayerService(playerId)); + } + else if (CurrentMockMode == MockModeSelector.Browser) + { + player = new Player(playerId, + new BrowserMockPlayerService(UnityBrowserBridge.Instance, playerId)); + } } else { @@ -85,66 +108,98 @@ public static Player GetPlayer(string playerId) return player; } } - + + public static Player GetPlayerById(string playerId) + { + if (Players.TryGetValue(playerId, out var player)) + { + return player; + } + else + { + if (!IsRunningInBrowser()) + { + if (CurrentMockMode == MockModeSelector.Local) + { + player = new Player(playerId, new Player.LocalPlayerService(playerId)); + } + else if (CurrentMockMode == MockModeSelector.Browser) + { + player = new Player(playerId, + new BrowserMockPlayerService(UnityBrowserBridge.Instance, playerId)); + } + } + else + { + player = new Player(playerId, new Player.PlayerService(playerId)); + } + + Players.Add(playerId, player); + return player; + } + } + public void SetState(string key, T value, bool reliable = false) { - if (!isPlayRoomInitialized) + if (!IsPlayRoomInitialized) { Debug.LogError("PlayroomKit is not loaded!. Please make sure to call InsertCoin first."); return; } + _playroomService.SetState(key, value, reliable); } - + public T GetState(string key) { - if (!isPlayRoomInitialized) + if (!IsPlayRoomInitialized) { Debug.LogError("PlayroomKit is not loaded!. Please make sure to call InsertCoin first."); return default; } + return _playroomService.GetState(key); } - + public void RpcRegister(string name, Action rpcRegisterCallback, string onResponseReturn = null) { - if (!isPlayRoomInitialized) + if (!IsPlayRoomInitialized) { Debug.LogError("PlayroomKit is not loaded!. Please make sure to call InsertCoin first."); return; } - + _rpc.RpcRegister(name, rpcRegisterCallback, onResponseReturn); } - + public void RpcCall(string name, object data, Action callbackOnResponse = null) { - if (!isPlayRoomInitialized) + if (!IsPlayRoomInitialized) { Debug.LogError("PlayroomKit is not loaded!. Please make sure to call InsertCoin first."); return; } - + _rpc.RpcCall(name, data, callbackOnResponse); } - + public void RpcCall(string name, object data, RpcMode mode, Action callbackOnResponse = null) { - if (!isPlayRoomInitialized) + if (!IsPlayRoomInitialized) { Debug.LogError("PlayroomKit is not loaded!. Please make sure to call InsertCoin first."); return; } - + _rpc.RpcCall(name, data, mode, callbackOnResponse); } - + public void StartMatchmaking(Action callback = null) { _playroomService.StartMatchmaking(callback); } - + // it checks if the game is running in the browser or in the editor public static bool IsRunningInBrowser() { @@ -154,56 +209,57 @@ public static bool IsRunningInBrowser() return false; #endif } - + public static Dictionary GetPlayers() { return Players; } - + public string GetRoomCode() { return _playroomService.GetRoomCode(); } - - - public void OnDisconnect(Action callback) + + + public void OnDisconnect(Action callback) { _playroomService.OnDisconnect(callback); } - + public bool IsStreamScreen() { - if (!isPlayRoomInitialized) + if (!IsPlayRoomInitialized) { Debug.LogError("[Mock Mode] Playroom not initialized yet! Please call InsertCoin."); return false; } - + return _playroomService.IsStreamScreen(); } - + public void WaitForState(string stateKey, Action onStateSetCallback = null) { _playroomService.WaitForState(stateKey, onStateSetCallback); } - + public void WaitForPlayerState(string playerID, string stateKey, Action onStateSetCallback = null) { _playroomService.WaitForPlayerState(playerID, stateKey, onStateSetCallback); } - + public void ResetStates(string[] keysToExclude = null, Action OnStatesReset = null) { _playroomService.ResetStates(keysToExclude, OnStatesReset); } - + public void ResetPlayersStates(string[] keysToExclude = null, Action OnStatesReset = null) { _playroomService.ResetPlayersStates(keysToExclude, OnStatesReset); + } - + // Joystick - public void CreateJoyStick(JoystickOptions options) + public void CreateJoyStick(JoystickOptions options) { _playroomService.CreateJoyStick(options); } @@ -212,34 +268,34 @@ public Dpad DpadJoystick() { return _playroomService.DpadJoystick(); } - + public Player MyPlayer() { - if (!isPlayRoomInitialized) + if (!IsPlayRoomInitialized) { Debug.LogError("[Mock Mode] Playroom not initialized yet! Please call InsertCoin."); return null; } + return _playroomService.MyPlayer(); } public Player Me() { - if (!isPlayRoomInitialized) + if (!IsPlayRoomInitialized) { Debug.LogError("[Mock Mode] Playroom not initialized yet! Please call InsertCoin."); return null; } - + return _playroomService.Me(); } - + private void UnsubscribeOnQuit() { _playroomService.UnsubscribeOnQuit(); } - + // DI END - } } \ No newline at end of file diff --git a/Assets/PlayroomKit/Prefabs/PlayroomMockManager.prefab b/Assets/PlayroomKit/Prefabs/PlayroomMockManager.prefab index 6b660be..2b72a67 100644 --- a/Assets/PlayroomKit/Prefabs/PlayroomMockManager.prefab +++ b/Assets/PlayroomKit/Prefabs/PlayroomMockManager.prefab @@ -1,6 +1,6 @@ %YAML 1.1 %TAG !u! tag:unity3d.com,2011: ---- !u!1 &1488774288987972492 +--- !u!1 &1824217503633254899 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} @@ -8,8 +8,56 @@ GameObject: m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - - component: {fileID: 1488774288987972494} - - component: {fileID: 1488774288987972495} + - component: {fileID: 4611920177403363027} + - component: {fileID: 8987662522597341863} + m_Layer: 0 + m_Name: PlayroomMockManager + m_TagString: EditorOnly + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &4611920177403363027 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1824217503633254899} + serializedVersion: 2 + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: -0.3, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_ConstrainProportionsScale: 0 + m_Children: + - {fileID: 3702849331354155344} + - {fileID: 3958277020740700826} + m_Father: {fileID: 0} + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!114 &8987662522597341863 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1824217503633254899} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 120dfa1b0ad7e96479cb0286e61ad19d, type: 3} + m_Name: + m_EditorClassIdentifier: + mockMode: 1 + insertCoinCaller: {fileID: 0} +--- !u!1 &5935941862803782869 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 3702849331354155344} + - component: {fileID: 8899696337967424923} m_Layer: 0 m_Name: UnityBrowserBridge m_TagString: EditorOnly @@ -17,28 +65,28 @@ GameObject: m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 ---- !u!4 &1488774288987972494 +--- !u!4 &3702849331354155344 Transform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} - m_GameObject: {fileID: 1488774288987972492} + m_GameObject: {fileID: 5935941862803782869} serializedVersion: 2 m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} m_ConstrainProportionsScale: 0 m_Children: [] - m_Father: {fileID: 3746181030263044757} + m_Father: {fileID: 4611920177403363027} m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} ---- !u!114 &1488774288987972495 +--- !u!114 &8899696337967424923 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} - m_GameObject: {fileID: 1488774288987972492} + m_GameObject: {fileID: 5935941862803782869} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 20e679ddcc87f49cd93e72eaa0e674bf, type: 3} @@ -50,8 +98,8 @@ MonoBehaviour: httpServerPort: 6500 indexFile: {fileID: 4900000, guid: f9b34a310cdb64b38a68c4c1319bf1a7, type: 3} includeJavaScriptFiles: - - Playroomkit\modules\PlayroomMockBridge.js ---- !u!1 &1957495583081457048 + - Assets\PlayroomKit\modules\MockMode\BrowserMode\PlayroomMockBrowserBridge.js +--- !u!1 &7050488703328543825 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} @@ -59,42 +107,40 @@ GameObject: m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - - component: {fileID: 3746181030263044757} - - component: {fileID: 5593001685836374760} + - component: {fileID: 3958277020740700826} + - component: {fileID: 6691438448404253686} m_Layer: 0 - m_Name: PlayroomMockManager - m_TagString: EditorOnly + m_Name: CallbackManager + m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 ---- !u!4 &3746181030263044757 +--- !u!4 &3958277020740700826 Transform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} - m_GameObject: {fileID: 1957495583081457048} + m_GameObject: {fileID: 7050488703328543825} serializedVersion: 2 m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} - m_LocalPosition: {x: -0.3, y: 0, z: 0} + m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} m_ConstrainProportionsScale: 0 - m_Children: - - {fileID: 1488774288987972494} - m_Father: {fileID: 0} + m_Children: [] + m_Father: {fileID: 4611920177403363027} m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} ---- !u!114 &5593001685836374760 +--- !u!114 &6691438448404253686 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} - m_GameObject: {fileID: 1957495583081457048} + m_GameObject: {fileID: 7050488703328543825} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 11500000, guid: 120dfa1b0ad7e96479cb0286e61ad19d, type: 3} + m_Script: {fileID: 11500000, guid: 0c683e101e93467a88e73140818eb8c8, type: 3} m_Name: m_EditorClassIdentifier: - mockMode: 0 - insertCoinCaller: {fileID: 0} + manager: {fileID: 8987662522597341863} diff --git a/Assets/PlayroomKit/Tests/Editor/PlayerLocalTests.cs b/Assets/PlayroomKit/Tests/Editor/PlayerLocalTests.cs index 363a2fc..8c10052 100644 --- a/Assets/PlayroomKit/Tests/Editor/PlayerLocalTests.cs +++ b/Assets/PlayroomKit/Tests/Editor/PlayerLocalTests.cs @@ -1,49 +1,50 @@ -using System; -using System.Globalization; using NUnit.Framework; -using NSubstitute; // For mocking the IPlayerService interface using Playroom; using UnityEngine; +// For mocking the IPlayerService interface -public class PlayerLocalTests +namespace Playroom.Tests.Editor { - private PlayroomKit _playroomKit; - private PlayroomKit.Player _player; - private PlayroomKit.Player.IPlayerBase _mockPlayerService; - private PlayroomKit.IInterop _interop; + public class PlayerLocalTests + { + private Playroom.PlayroomKit _playroomKit; + private Playroom.PlayroomKit.Player _player; + private Playroom.PlayroomKit.Player.IPlayerBase _mockPlayerService; + private Playroom.PlayroomKit.IInterop _interop; - private string testId = "test_player_id"; + private string testId = "test_player_id"; - [SetUp] - public void SetUp() - { - var _playroomKitService = new PlayroomKit.LocalMockPlayroomService(); - _playroomKit = new PlayroomKit(_playroomKitService, new PlayroomKit.RPCLocal()); - _playroomKit.InsertCoin(new InitOptions() + [SetUp] + public void SetUp() { - maxPlayersPerRoom = 2, - defaultPlayerStates = new() { { "score", 0 }, }, - }, () => { }); - // Mock the IPlayerService - _mockPlayerService = new PlayroomKit.Player.LocalPlayerService(testId); + var _playroomKitService = new LocalMockPlayroomService(); + _playroomKit = new Playroom.PlayroomKit(_playroomKitService, new Playroom.PlayroomKit.RPCLocal()); + _playroomKit.InsertCoin(new InitOptions() + { + maxPlayersPerRoom = 2, + defaultPlayerStates = new() { { "score", 0 }, }, + }, () => { }); + // Mock the IPlayerService + _mockPlayerService = new Playroom.PlayroomKit.Player.LocalPlayerService(testId); - // Create a new Player object with the mock service - _player = new PlayroomKit.Player(testId, _mockPlayerService); - } + // Create a new Player object with the mock service + _player = new Playroom.PlayroomKit.Player(testId, _mockPlayerService); + } - [Test] - public void WaitForState_RegisterCallback() - { - _player.WaitForState("winner", (data) => + [Test] + public void WaitForState_RegisterCallback() { - Debug.Log("winner data: " + data); - Assert.IsTrue(bool.Parse(data), "Callback should be invoked"); - }); - } + _player.WaitForState("winner", (data) => + { + Debug.Log("winner data: " + data); + Assert.IsTrue(bool.Parse(data), "Callback should be invoked"); + }); + } - [Test] - public void WaitForState_ShouldBeInvokedWhenSetIsSet() - { - _player.SetState("winner", true); + [Test] + public void WaitForState_ShouldBeInvokedWhenSetIsSet() + { + _player.SetState("winner", true); + } } } \ No newline at end of file diff --git a/Assets/PlayroomKit/Tests/Editor/PlayerTests.cs b/Assets/PlayroomKit/Tests/Editor/PlayerTests.cs index f41f2ed..be690f9 100644 --- a/Assets/PlayroomKit/Tests/Editor/PlayerTests.cs +++ b/Assets/PlayroomKit/Tests/Editor/PlayerTests.cs @@ -5,261 +5,265 @@ using Playroom; using UnityEngine; -public class PlayerTests +namespace Playroom.Tests.Editor { - private PlayroomKit _playroomKit; - private PlayroomKit.Player _player; - private PlayroomKit.Player.IPlayerBase _mockPlayerService; - private PlayroomKit.IInterop _interop; - - private string testId = "test_player_id"; - private string testKey = "test_key"; - - [SetUp] - public void SetUp() + public class PlayerTests { - _playroomKit = new PlayroomKit(); - _playroomKit.InsertCoin(new InitOptions() - { - maxPlayersPerRoom = 2, - defaultPlayerStates = new() { { "score", 0 }, }, - }, () => { }); - _interop = Substitute.For(); - // Mock the IPlayerService - _mockPlayerService = new PlayroomKit.Player.PlayerService(testId, _interop); - - // Create a new Player object with the mock service - _player = new PlayroomKit.Player(testId, _mockPlayerService); - } + private PlayroomKit _playroomKit; + private PlayroomKit.Player _player; + private PlayroomKit.Player.IPlayerBase _mockPlayerService; + private PlayroomKit.IInterop _interop; - [Test] - public void SetState_Int_CallsIntWrapperWithCorrectParameters() - { - // Arrange - int testValue = 100; - bool reliable = true; + private string testId = "test_player_id"; + private string testKey = "test_key"; - // Act - _player.SetState(testKey, testValue, reliable); + [SetUp] + public void SetUp() + { + _playroomKit = new PlayroomKit(); + _playroomKit.InsertCoin(new InitOptions() + { + maxPlayersPerRoom = 2, + defaultPlayerStates = new() { { "score", 0 }, }, + }, () => { }); + _interop = Substitute.For(); + // Mock the IPlayerService + _mockPlayerService = new PlayroomKit.Player.PlayerService(testId, _interop); + + // Create a new Player object with the mock service + _player = new PlayroomKit.Player(testId, _mockPlayerService); + } + + [Test] + public void SetState_Int_CallsIntWrapperWithCorrectParameters() + { + // Arrange + int testValue = 100; + bool reliable = true; - // Assert - _interop.Received(1).SetPlayerStateIntWrapper(testId, testKey, testValue, reliable); - } + // Act + _player.SetState(testKey, testValue, reliable); - [Test] - public void SetState_Float_CallsFloatWrapperWithCorrectParameters() - { - // Arrange - float testValue = 3.14f; - bool reliable = false; + // Assert + _interop.Received(1).SetPlayerStateIntWrapper(testId, testKey, testValue, reliable); + } - // Act - _player.SetState(testKey, testValue, reliable); + [Test] + public void SetState_Float_CallsFloatWrapperWithCorrectParameters() + { + // Arrange + float testValue = 3.14f; + bool reliable = false; - // Assert - _interop.Received(1) - .SetPlayerStateFloatWrapper(testId, testKey, testValue.ToString(CultureInfo.InvariantCulture), reliable); - } + // Act + _player.SetState(testKey, testValue, reliable); - [Test] - public void SetState_Bool_CallsBoolWrapperWithCorrectParameters() - { - // Arrange - bool testValue = true; - bool reliable = true; + // Assert + _interop.Received(1) + .SetPlayerStateFloatWrapper(testId, testKey, testValue.ToString(CultureInfo.InvariantCulture), + reliable); + } - // Act - _player.SetState(testKey, testValue, reliable); + [Test] + public void SetState_Bool_CallsBoolWrapperWithCorrectParameters() + { + // Arrange + bool testValue = true; + bool reliable = true; - // Assert - _interop.Received(1).SetPlayerStateBoolWrapper(testId, testKey, testValue, reliable); - } + // Act + _player.SetState(testKey, testValue, reliable); - [Test] - public void SetState_String_CallsStringWrapperWithCorrectParameters() - { - // Arrange - string testValue = "TestValue"; - bool reliable = false; + // Assert + _interop.Received(1).SetPlayerStateBoolWrapper(testId, testKey, testValue, reliable); + } - // Act - _player.SetState(testKey, testValue, reliable); + [Test] + public void SetState_String_CallsStringWrapperWithCorrectParameters() + { + // Arrange + string testValue = "TestValue"; + bool reliable = false; - // Assert - _interop.Received(1).SetPlayerStateStringWrapper(testId, testKey, testValue, reliable); - } + // Act + _player.SetState(testKey, testValue, reliable); - [Test] - public void SetState_Object_CallsObjectWrapperWithSerializedJson() - { - // Arrange - var testObject = new { testProperty = "Test" }; - bool reliable = true; - string expectedJson = JsonUtility.ToJson(testObject); + // Assert + _interop.Received(1).SetPlayerStateStringWrapper(testId, testKey, testValue, reliable); + } - // Act - _player.SetState(testKey, testObject, reliable); + [Test] + public void SetState_Object_CallsObjectWrapperWithSerializedJson() + { + // Arrange + var testObject = new { testProperty = "Test" }; + bool reliable = true; + string expectedJson = JsonUtility.ToJson(testObject); - // Assert - _interop.Received(1).SetPlayerStateStringWrapper(testId, testKey, expectedJson, reliable); - } + // Act + _player.SetState(testKey, testObject, reliable); + // Assert + _interop.Received(1).SetPlayerStateStringWrapper(testId, testKey, expectedJson, reliable); + } - [Test] - public void GetState_ShouldReturnCorrectValue_FromPlayerService() - { - // Arrange - string key = "health"; - int expectedValue = 100; - // Mock the return value from GetState - _mockPlayerService.GetState(key).Returns(expectedValue); + [Test] + public void GetState_ShouldReturnCorrectValue_FromPlayerService() + { + // Arrange + string key = "health"; + int expectedValue = 100; - // Act - int result = _player.GetState(key); + // Mock the return value from GetState + _mockPlayerService.GetState(key).Returns(expectedValue); - // Assert - Assert.AreEqual(expectedValue, result, "GetState should return the correct value."); - } + // Act + int result = _player.GetState(key); - [Test] - public void GetState_ShouldWorkWithDifferentTypes() - { - // Arrange - string stringKey = "name"; - string expectedStringValue = "Player1"; + // Assert + Assert.AreEqual(expectedValue, result, "GetState should return the correct value."); + } - string intKey = "score"; - int expectedIntValue = 200; + [Test] + public void GetState_ShouldWorkWithDifferentTypes() + { + // Arrange + string stringKey = "name"; + string expectedStringValue = "Player1"; - // Mock the return values from GetState - _mockPlayerService.GetState(stringKey).Returns(expectedStringValue); - _mockPlayerService.GetState(intKey).Returns(expectedIntValue); + string intKey = "score"; + int expectedIntValue = 200; - // Act - string name = _player.GetState(stringKey); - int score = _player.GetState(intKey); + // Mock the return values from GetState + _mockPlayerService.GetState(stringKey).Returns(expectedStringValue); + _mockPlayerService.GetState(intKey).Returns(expectedIntValue); - // Assert - Assert.AreEqual(expectedStringValue, name, "GetState should return the correct string value."); - Assert.AreEqual(expectedIntValue, score, "GetState should return the correct int value."); - } + // Act + string name = _player.GetState(stringKey); + int score = _player.GetState(intKey); - [Test] - public void GetProfile_ShouldReturnProfileWithParsedData() - { - // Mock JSON string that GetProfileWrapper would return - string jsonString = - "{\"name\": \"PlayerName\", \"photo\": \"player_photo_url\", \"color\": { \"r\": 255, \"g\": 128, \"b\": 64, \"hexString\": \"#FF8040\", \"hex\": 16744448 }}"; + // Assert + Assert.AreEqual(expectedStringValue, name, "GetState should return the correct string value."); + Assert.AreEqual(expectedIntValue, score, "GetState should return the correct int value."); + } - // Define the expected Profile object - var expectedProfile = new PlayroomKit.Player.Profile + [Test] + public void GetProfile_ShouldReturnProfileWithParsedData() { - name = "PlayerName", - photo = "player_photo_url", - playerProfileColor = new PlayroomKit.Player.Profile.PlayerProfileColor + // Mock JSON string that GetProfileWrapper would return + string jsonString = + "{\"name\": \"PlayerName\", \"photo\": \"player_photo_url\", \"color\": { \"r\": 255, \"g\": 128, \"b\": 64, \"hexString\": \"#FF8040\", \"hex\": 16744448 }}"; + + // Define the expected Profile object + var expectedProfile = new PlayroomKit.Player.Profile { - r = 255, - g = 128, - b = 64, - hexString = "#FF8040", - hex = 16744448 - } - }; - - // Mock the GetProfileWrapper method to return the predefined JSON string - _interop.GetProfileWrapper(testId).Returns(jsonString); - - - // Act - var result = _player.GetProfile(); - - _interop.Received(1).GetProfileWrapper(testId); - - // Assert with error messages - Assert.AreEqual(expectedProfile.name, result.name, "Profile name did not match the expected value."); - Assert.AreEqual(expectedProfile.photo, result.photo, "Profile photo did not match the expected URL."); - Assert.AreEqual(expectedProfile.playerProfileColor.r, result.playerProfileColor.r, - "Player profile color red value did not match."); - Assert.AreEqual(expectedProfile.playerProfileColor.g, result.playerProfileColor.g, - "Player profile color green value did not match."); - Assert.AreEqual(expectedProfile.playerProfileColor.b, result.playerProfileColor.b, - "Player profile color blue value did not match."); - Assert.AreEqual(expectedProfile.playerProfileColor.hexString, result.playerProfileColor.hexString, - "Player profile color hex string did not match."); - Assert.AreEqual(expectedProfile.playerProfileColor.hex, result.playerProfileColor.hex, - "Player profile color hex value did not match."); - } + name = "PlayerName", + photo = "player_photo_url", + playerProfileColor = new PlayroomKit.Player.Profile.PlayerProfileColor + { + r = 255, + g = 128, + b = 64, + hexString = "#FF8040", + hex = 16744448 + } + }; + + // Mock the GetProfileWrapper method to return the predefined JSON string + _interop.GetProfileWrapper(testId).Returns(jsonString); + + + // Act + var result = _player.GetProfile(); + + _interop.Received(1).GetProfileWrapper(testId); + + // Assert with error messages + Assert.AreEqual(expectedProfile.name, result.name, "Profile name did not match the expected value."); + Assert.AreEqual(expectedProfile.photo, result.photo, "Profile photo did not match the expected URL."); + Assert.AreEqual(expectedProfile.playerProfileColor.r, result.playerProfileColor.r, + "Player profile color red value did not match."); + Assert.AreEqual(expectedProfile.playerProfileColor.g, result.playerProfileColor.g, + "Player profile color green value did not match."); + Assert.AreEqual(expectedProfile.playerProfileColor.b, result.playerProfileColor.b, + "Player profile color blue value did not match."); + Assert.AreEqual(expectedProfile.playerProfileColor.hexString, result.playerProfileColor.hexString, + "Player profile color hex string did not match."); + Assert.AreEqual(expectedProfile.playerProfileColor.hex, result.playerProfileColor.hex, + "Player profile color hex value did not match."); + } + + [Test] + public void OnQuit_WhenInitialized_AddsCallbackAndReturnsUnsubscribeAction() + { + // Arrange + Action callback = msg => { }; - [Test] - public void OnQuit_WhenInitialized_AddsCallbackAndReturnsUnsubscribeAction() - { - // Arrange - Action callback = msg => { }; + // Act + var unsubscribe = _player.OnQuit(callback); - // Act - var unsubscribe = _player.OnQuit(callback); + // Assert + Assert.IsNotNull(unsubscribe, "Expected unsubscribe action to be returned."); - // Assert - Assert.IsNotNull(unsubscribe, "Expected unsubscribe action to be returned."); + // Check that the callback is added to the list + unsubscribe.Invoke(); // Calling unsubscribe should remove the callback - // Check that the callback is added to the list - unsubscribe.Invoke(); // Calling unsubscribe should remove the callback + // Internal check: Ensure callback list no longer contains the callback after unsubscribe + } - // Internal check: Ensure callback list no longer contains the callback after unsubscribe - } + [Test] + public void Kick_WhenInitialized_CallsKickPlayerWrapperWithCorrectParameters() + { + // Arrange + Action onKickCallback = () => { }; - [Test] - public void Kick_WhenInitialized_CallsKickPlayerWrapperWithCorrectParameters() - { - // Arrange - Action onKickCallback = () => { }; + // Act + _player.Kick(onKickCallback); - // Act - _player.Kick(onKickCallback); + // Assert + _interop.Received(1).KickPlayerWrapper(testId, Arg.Any()); + } - // Assert - _interop.Received(1).KickPlayerWrapper(testId, Arg.Any()); - } - - [Test] - public void Kick_CallsInvokeKickInternal_CallbackIsInvoked() - { - // Arrange - bool callbackInvoked = false; - Action onKickCallback = () => { callbackInvoked = true; }; + [Test] + public void Kick_CallsInvokeKickInternal_CallbackIsInvoked() + { + // Arrange + bool callbackInvoked = false; + Action onKickCallback = () => { callbackInvoked = true; }; - // Set up the mock to invoke the callback when KickPlayerWrapper is called - _interop.When(x => x.KickPlayerWrapper( - Arg.Any(), // id - Arg.Any() // onKick callback - )) - .Do(callInfo => - { - var kickCallback = callInfo.ArgAt(1); // Correct index for the callback argument - kickCallback?.Invoke(); // Invoke the callback - }); + // Set up the mock to invoke the callback when KickPlayerWrapper is called + _interop.When(x => x.KickPlayerWrapper( + Arg.Any(), // id + Arg.Any() // onKick callback + )) + .Do(callInfo => + { + var kickCallback = callInfo.ArgAt(1); // Correct index for the callback argument + kickCallback?.Invoke(); // Invoke the callback + }); - //Act - _player.Kick(onKickCallback); + //Act + _player.Kick(onKickCallback); - // Assert - _interop.Received(1).KickPlayerWrapper(testId, Arg.Invoke()); - Assert.IsTrue(callbackInvoked, "Expected the onKickCallback to be invoked."); - } + // Assert + _interop.Received(1).KickPlayerWrapper(testId, Arg.Invoke()); + Assert.IsTrue(callbackInvoked, "Expected the onKickCallback to be invoked."); + } - [Test] - public void WaitForState_WhenInitialized_CallsWaitForPlayerStateWrapperWithCorrectParameters() - { - // Arrange - Action onStateSetCallback = (data) => { Debug.Log("data: " + data); }; + [Test] + public void WaitForState_WhenInitialized_CallsWaitForPlayerStateWrapperWithCorrectParameters() + { + // Arrange + Action onStateSetCallback = (data) => { Debug.Log("data: " + data); }; - // Act - _player.WaitForState(testKey, onStateSetCallback); + // Act + _player.WaitForState(testKey, onStateSetCallback); - // Assert - _interop.Received(1).WaitForPlayerStateWrapper(testId, testKey, onStateSetCallback); + // Assert + _interop.Received(1).WaitForPlayerStateWrapper(testId, testKey, onStateSetCallback); + } } } \ No newline at end of file diff --git a/Assets/PlayroomKit/Tests/Editor/PlayroomKitLocalTests.cs b/Assets/PlayroomKit/Tests/Editor/PlayroomKitLocalTests.cs index 4c371e2..2e331cc 100644 --- a/Assets/PlayroomKit/Tests/Editor/PlayroomKitLocalTests.cs +++ b/Assets/PlayroomKit/Tests/Editor/PlayroomKitLocalTests.cs @@ -5,152 +5,137 @@ using Playroom; using NSubstitute; -public class PlayroomKitLocalTests +namespace Playroom.Tests.Editor { - private PlayroomKit _playroomKit; - private PlayroomKit.IPlayroomBase _mockPlayroomService; - private PlayroomKit.IInterop _interop; - private PlayroomKit.IRPC _rpc; - - [SetUp] - public void SetUp() + public class PlayroomKitLocalTests { - _interop = Substitute.For(); - // Initialize the mock PlayroomService - _mockPlayroomService = new PlayroomKit.LocalMockPlayroomService(); - _rpc = new PlayroomKit.RPC(_playroomKit, _interop); - // Since PlayroomKit uses a private field for the service, we'll need to simulate it or test through the public API - _playroomKit = new PlayroomKit(_mockPlayroomService, _rpc); - } - - [Test] - public void InsertCoin_ShouldBeInvoked() - { - var mockPlayroomService = Substitute.For(); - var playroomKit = new PlayroomKit(mockPlayroomService, _rpc); - - playroomKit.InsertCoin(new InitOptions() + private PlayroomKit _playroomKit; + private PlayroomKit.IPlayroomBase _mockPlayroomService; + private PlayroomKit.IInterop _interop; + private PlayroomKit.IRPC _rpc; + + [SetUp] + public void SetUp() { - maxPlayersPerRoom = 2, - defaultPlayerStates = new() { {"score", 0}, }, - }, () => + _interop = Substitute.For(); + _mockPlayroomService = new LocalMockPlayroomService(); + _rpc = new PlayroomKit.RPC(_playroomKit, _interop); + _playroomKit = new PlayroomKit(_mockPlayroomService, _rpc); + } + + [Test] + public void InsertCoin_ShouldBeInvoked() { - - }); - - mockPlayroomService.Received(1).InsertCoin(Arg.Any(),Arg.Any()); - } + var mockPlayroomService = Substitute.For(); + var playroomKit = new PlayroomKit(mockPlayroomService, _rpc); - [Test] - public void OnPlayerJoin_PlayerShouldBeAdded() - { - bool playerJoined = false; - var playroomKit = new PlayroomKit(new PlayroomKit.LocalMockPlayroomService(), _rpc); - - playroomKit.InsertCoin(new InitOptions() + playroomKit.InsertCoin(new InitOptions() + { + maxPlayersPerRoom = 2, + defaultPlayerStates = new() { { "score", 0 }, }, + }, () => { }); + + mockPlayroomService.Received(1).InsertCoin(Arg.Any(), Arg.Any()); + } + + [Test] + public void OnPlayerJoin_PlayerShouldBeAdded() { - maxPlayersPerRoom = 2, - defaultPlayerStates = new() { {"score", 0}, }, - }, () => + bool playerJoined = false; + var playroomKit = new PlayroomKit(new LocalMockPlayroomService(), _rpc); + + playroomKit.InsertCoin(new InitOptions() + { + maxPlayersPerRoom = 2, + defaultPlayerStates = new() { { "score", 0 }, }, + }, () => { }); + + playroomKit.OnPlayerJoin(player => + { + playerJoined = true; + Debug.Log(player.id); + }); + + Assert.IsTrue(playerJoined, "Callback should be invoked when player joins."); + } + + [Test] + public void GetRoomCode_ShouldReturnRoomCode() { - - }); - - playroomKit.OnPlayerJoin(player => + var roomCode = _playroomKit.GetRoomCode(); + Assert.AreEqual(roomCode, "mock123"); + } + + [Test] + public void StartMatchmaking_ShouldInvoke_StartMatchmakingLocal() { - playerJoined = true; - Debug.Log(player.id); - }); - - Assert.IsTrue(playerJoined, "Callback should be invoked when player joins."); - } - - [Test] - public void GetRoomCode_ShouldReturnRoomCode() - { - var roomCode = _playroomKit.GetRoomCode(); - Assert.AreEqual(roomCode, "mock123"); - } - - [Test] - public void StartMatchmaking_ShouldInvoke_StartMatchmakingLocal() - { - var mockPlayroomService = Substitute.For(); - - // Since PlayroomKit uses a private field for the service, we'll need to simulate it or test through the public API - var playroomKit = new PlayroomKit(mockPlayroomService, _rpc); - playroomKit.StartMatchmaking(); - - mockPlayroomService.Received(1).StartMatchmaking(Arg.Any()); - } - - [Test] - public void IsStreamScreen_ShouldReturnFalse_WhenCalled() - { - _playroomKit.InsertCoin(new InitOptions() + var mockPlayroomService = Substitute.For(); + + // Since PlayroomKit uses a private field for the service, we'll need to simulate it or test through the public API + var playroomKit = new PlayroomKit(mockPlayroomService, _rpc); + playroomKit.StartMatchmaking(); + + mockPlayroomService.Received(1).StartMatchmaking(Arg.Any()); + } + + [Test] + public void IsStreamScreen_ShouldReturnFalse_WhenCalled() { - maxPlayersPerRoom = 2, - defaultPlayerStates = new() { {"score", 0}, }, - }, () => + _playroomKit.InsertCoin(new InitOptions() + { + maxPlayersPerRoom = 2, + defaultPlayerStates = new() { { "score", 0 }, }, + }, () => { }); + + var isStream = _playroomKit.IsStreamScreen(); + Debug.Log(isStream); + Assert.IsFalse(isStream, "IsStreamScreen should be false."); + } + + [Test] + public void ResetStates_ShouldInvokeCallback() { - - }); + var keysToExclude = new[] { "pos" }; + bool callbackInvoked = false; - var isStream = _playroomKit.IsStreamScreen(); - Debug.Log(isStream); - Assert.IsFalse(isStream, "IsStreamScreen should be false."); - } - - [Test] - public void ResetStates_ShouldInvokeCallback() - { - var keysToExclude = new[] { "pos" }; - bool callbackInvoked = false; + // Act + _playroomKit.ResetStates(keysToExclude, () => callbackInvoked = true); - // Act - _playroomKit.ResetStates(keysToExclude, () => callbackInvoked = true); - - Assert.IsTrue(callbackInvoked, "Callback should be invoked"); - } - - [Test] - public void ResetPlayersStates_InvokeCallback() - { - // Arrange - var keysToExclude = new[] { "pos" }; - bool callbackInvoked = false; - - // Act - _playroomKit.ResetPlayersStates(keysToExclude, () => callbackInvoked = true); - - //Assert - Assert.IsTrue(callbackInvoked, "Callback should be invoked"); - } - - [Test] - public void MyPlayer_ReturnLocalPlayer() - { - var expectedPlayer = PlayroomKit.GetPlayer("mockplayerID123"); - var player = _playroomKit.MyPlayer(); - Assert.AreEqual(expectedPlayer, player); - } + Assert.IsTrue(callbackInvoked, "Callback should be invoked"); + } + [Test] + public void ResetPlayersStates_InvokeCallback() + { + // Arrange + var keysToExclude = new[] { "pos" }; + bool callbackInvoked = false; - [Test] - public void WaitForState_ShouldInvokeCallback_WhenStateIsSet() - { - bool callbackInvoked = false; - _playroomKit.WaitForState("winner", key => + // Act + _playroomKit.ResetPlayersStates(keysToExclude, () => callbackInvoked = true); + + //Assert + Assert.IsTrue(callbackInvoked, "Callback should be invoked"); + } + + [Test] + public void MyPlayer_ReturnLocalPlayer() { - callbackInvoked = true; - }); - - _playroomKit.SetState("winner", true); - - Assert.IsTrue(callbackInvoked, "Callback should be invoked"); - } + var expectedPlayer = _playroomKit.GetPlayer("mockplayerID123"); + var player = _playroomKit.MyPlayer(); + Assert.AreEqual(expectedPlayer, player); + } + + [Test] + public void WaitForState_ShouldInvokeCallback_WhenStateIsSet() + { + bool callbackInvoked = false; + _playroomKit.WaitForState("winner", key => { callbackInvoked = true; }); + _playroomKit.SetState("winner", true); - -} + Assert.IsTrue(callbackInvoked, "Callback should be invoked"); + } + } +} \ No newline at end of file diff --git a/Assets/PlayroomKit/Tests/Editor/PlayroomKitTest.cs b/Assets/PlayroomKit/Tests/Editor/PlayroomKitTest.cs index ceed526..f2c58b6 100644 --- a/Assets/PlayroomKit/Tests/Editor/PlayroomKitTest.cs +++ b/Assets/PlayroomKit/Tests/Editor/PlayroomKitTest.cs @@ -1,11 +1,9 @@ using NUnit.Framework; using System; -using System.Collections.Generic; using UnityEngine; using Playroom; using NSubstitute; -using NSubstitute.ReceivedExtensions; -using SimpleJSON; // Mocking library, can use other mock libraries like Moq as well +using SimpleJSON; public class PlayroomKitTests { @@ -13,30 +11,28 @@ public class PlayroomKitTests private PlayroomKit.IPlayroomBase _mockPlayroomService; private PlayroomKit.IInterop _interop; private PlayroomKit.IRPC _rpc; - + [SetUp] public void SetUp() { _interop = Substitute.For(); // Initialize the mock PlayroomService - _mockPlayroomService = new PlayroomKit.PlayroomService(_interop); + _mockPlayroomService = new PlayroomKit.PlayroomBuildService(_interop); _rpc = new PlayroomKit.RPC(_playroomKit, _interop); - + // Since PlayroomKit uses a private field for the service, we'll need to simulate it or test through the public API _playroomKit = new PlayroomKit(_mockPlayroomService, _rpc); } - - [Test] public void GetPlayer_ShouldReturnSamePlayer_ForSameId() { // Arrange string playerId = "Player1"; - + // Act - var player1 = PlayroomKit.GetPlayer(playerId); - var player2 = PlayroomKit.GetPlayer(playerId); + var player1 = _playroomKit.GetPlayer(playerId); + var player2 = _playroomKit.GetPlayer(playerId); // Assert Assert.AreEqual(player1, player2, "GetPlayer should return the same instance for the same playerId."); @@ -48,32 +44,30 @@ public void InternalInsertCoin_ShouldBeCalled() var interopMock = Substitute.For(); // No need to call DoNotCallBase() because it's an interface - PlayroomKit.IPlayroomBase playroomService = new PlayroomKit.PlayroomService(interopMock); + PlayroomKit.IPlayroomBase playroomService = new PlayroomKit.PlayroomBuildService(interopMock); PlayroomKit playroomKit = new PlayroomKit(playroomService, _rpc); playroomKit.InsertCoin(new InitOptions() { maxPlayersPerRoom = 2, - defaultPlayerStates = new() { {"score", 0}, }, - }, () => - { - Debug.Log("Insert Callback Received!"); - }); + defaultPlayerStates = new() { { "score", 0 }, }, + }, () => { Debug.Log("Insert Callback Received!"); }); interopMock.Received(1).InsertCoinWrapper( - Arg.Is(s => s.Contains("\"maxPlayersPerRoom\":2") && s.Contains("\"defaultPlayerStates\":{\"score\":0}")), // Check both maxPlayersPerRoom and defaultPlayerStates in the JSON - Arg.Any>(), // Any Action for the launch callback - Arg.Any>(), // Any Action for the quit handler - Arg.Any>(), // Any Action for the disconnect handler - Arg.Any>(), // Any Action for the error handler - Arg.Any(), // Any string for onLaunchCallBackKey - Arg.Any() // Any string for onDisconnectCallBackKey + Arg.Is(s => + s.Contains("\"maxPlayersPerRoom\":2") && + s.Contains( + "\"defaultPlayerStates\":{\"score\":0}")), // Check both maxPlayersPerRoom and defaultPlayerStates in the JSON + Arg.Any>(), // Any Action for the launch callback + Arg.Any>(), // Any Action for the quit handler + Arg.Any>(), // Any Action for the disconnect handler + Arg.Any>(), // Any Action for the error handler + Arg.Any(), // Any string for onLaunchCallBackKey + Arg.Any() // Any string for onDisconnectCallBackKey ); } - - [Test] public void InternalInsertCoin_LaunchCallBackShouldBeInvoked() { @@ -81,51 +75,49 @@ public void InternalInsertCoin_LaunchCallBackShouldBeInvoked() // Mocking the InsertCoinWrapper method behavior // Mocking the InsertCoinWrapper method behavior interopMock.When(x => x.InsertCoinWrapper( - Arg.Any(), // options JSON + Arg.Any(), // options JSON Arg.Any>(), // onLaunch callback Arg.Any>(), // onQuit callback Arg.Any>(), // onDisconnect callback Arg.Any>(), // onError callback - Arg.Any(), // onLaunch callback key - Arg.Any() // onDisconnect callback key + Arg.Any(), // onLaunch callback key + Arg.Any() // onDisconnect callback key )) - .Do(callInfo => { + .Do(callInfo => + { // Check if the callback is at the expected index and invoke it var onLaunchCallback = callInfo.ArgAt>(1); // Index 1 for onLaunch callback onLaunchCallback?.Invoke("onLaunchCallBack"); // Invoke the callback with a test key }); - - PlayroomKit.IPlayroomBase playroomService = new PlayroomKit.PlayroomService(interopMock); + + PlayroomKit.IPlayroomBase playroomService = new PlayroomKit.PlayroomBuildService(interopMock); PlayroomKit playroomKit = new PlayroomKit(playroomService, _rpc); - + bool onLaunchInvoked = false; playroomKit.InsertCoin(new InitOptions() { maxPlayersPerRoom = 2, - defaultPlayerStates = new() { {"score", 0}, }, - }, () => - { - onLaunchInvoked = true; - }); - + defaultPlayerStates = new() { { "score", 0 }, }, + }, () => { onLaunchInvoked = true; }); + Assert.True(onLaunchInvoked); } - + [Test] public void GetPlayer_ShouldCreateNewPlayer_IfNotExists() { // Arrange string newPlayerId = "Player2"; - + // Act - var player = PlayroomKit.GetPlayer(newPlayerId); + var player = _playroomKit.GetPlayer(newPlayerId); // Assert Assert.IsNotNull(player, "GetPlayer should create a new Player if one does not exist."); Assert.AreEqual(newPlayerId, player.id, "The Player's Id should match the requested playerId."); } - + [Test] public void OnPlayerJoinBuild_ShouldInvokeCallback_WhenPlayerJoins() { @@ -136,58 +128,56 @@ public void OnPlayerJoinBuild_ShouldInvokeCallback_WhenPlayerJoins() _playroomKit.InsertCoin(new InitOptions() { maxPlayersPerRoom = 2, - defaultPlayerStates = new() { {"score", 0}, }, - }, () => - { - - }); - + defaultPlayerStates = new() { { "score", 0 }, }, + }, () => { }); + _interop.When(x => x.OnPlayerJoinWrapper( Arg.Any>() // OnPlayerJoinCallback )) - .Do(callInfo => { + .Do(callInfo => + { // Check if the callback is at the expected index and invoke it var onPlayerJoin = callInfo.ArgAt>(0); // Index 1 for onLaunch callback onPlayerJoin?.Invoke(playerId); // Invoke the callback with a test key }); - - + + // Act - _playroomKit.OnPlayerJoin(player => + _playroomKit.OnPlayerJoin(player => { testPlayer = player; Debug.Log("OnPlayerJoin player id: " + player.id); playerCreated = true; }); - + var players = PlayroomKit.GetPlayers(); - + // Assert Assert.IsTrue(playerCreated, "Callback should be invoked when player joins."); Assert.AreEqual(playerId, testPlayer.id, "The Player's Id should match the requested player."); Assert.Greater(players.Count, 0, "The players count should be greater than zero."); } - + [Test] public void GetRoomCode_ShouldInvoke_GetRoomCodeInternal() { var roomCode = _playroomKit.GetRoomCode(); _interop.Received(1).GetRoomCodeWrapper(); } - + [Test] public void StartMatchmaking_ShouldInvoke_StartMatchmakingInternal() { _playroomKit.StartMatchmaking(); _interop.Received(1).StartMatchmakingWrapper(Arg.Any()); } - + public class TestObject { public string Name { get; set; } public int Value { get; set; } } - + [Test] public void SetState_ShouldInvokeCorrectInternalFunction_ForAllTypes() { @@ -197,7 +187,8 @@ public void SetState_ShouldInvokeCorrectInternalFunction_ForAllTypes() // Act & Assert for float _playroomKit.SetState("TestState", 1.23f); // For float - _interop.Received(1).SetStateFloatWrapper("TestState", "1.23", Arg.Any()); // Assuming float is serialized as string + _interop.Received(1) + .SetStateFloatWrapper("TestState", "1.23", Arg.Any()); // Assuming float is serialized as string // Act & Assert for string _playroomKit.SetState("TestState", "TestValue"); // For string @@ -217,75 +208,73 @@ public void SetState_ShouldInvokeCorrectInternalFunction_ForAllTypes() } [Test] -public void GetState_ShouldInvokeCorrectInternalFunction_ForAllTypes() -{ - // Arrange & Act for int - _interop.GetStateIntWrapper("TestState").Returns(42); // Mock for int - var intValue = _playroomKit.GetState("TestState"); - // Assert for int - Assert.AreEqual(42, intValue); - _interop.Received(1).GetStateIntWrapper("TestState"); - - // Arrange & Act for float - _interop.GetStateFloatWrapper("TestState").Returns(3.14f); // Mock for float - var floatValue = _playroomKit.GetState("TestState"); - // Assert for float - Assert.AreEqual(3.14f, floatValue); - _interop.Received(1).GetStateFloatWrapper("TestState"); - - // Arrange & Act for bool - _interop.GetStateIntWrapper("TestState").Returns(1); // Mock for bool - var boolValue = _playroomKit.GetState("TestState"); - // Assert for bool - Assert.IsTrue(boolValue); - _interop.Received(2).GetStateIntWrapper("TestState"); - - // Arrange & Act for string - _interop.GetStateStringWrapper("TestState").Returns("TestValue"); // Mock for string - var stringValue = _playroomKit.GetState("TestState"); - // Assert for string - Assert.AreEqual("TestValue", stringValue); - _interop.Received(1).GetStateStringWrapper("TestState"); - - // Arrange & Act for Vector2 - var vector2Json = JsonUtility.ToJson(new Vector2(1.0f, 2.0f)); - _interop.GetStateStringWrapper("TestState").Returns(vector2Json); // Mock for Vector2 as JSON - var vector2Value = _playroomKit.GetState("TestState"); - // Assert for Vector2 - Assert.AreEqual(new Vector2(1.0f, 2.0f), vector2Value); - _interop.Received(2).GetStateStringWrapper("TestState"); - - // Arrange & Act for Vector3 - var vector3Json = JsonUtility.ToJson(new Vector3(1.0f, 2.0f, 3.0f)); - _interop.GetStateStringWrapper("TestState").Returns(vector3Json); // Mock for Vector3 as JSON - var vector3Value = _playroomKit.GetState("TestState"); - // Assert for Vector3 - Assert.AreEqual(new Vector3(1.0f, 2.0f, 3.0f), vector3Value); - _interop.Received(3).GetStateStringWrapper("TestState"); - - // Arrange & Act for Vector4 - var vector4Json = JsonUtility.ToJson(new Vector4(1.0f, 2.0f, 3.0f, 4.0f)); - _interop.GetStateStringWrapper("TestState").Returns(vector4Json); // Mock for Vector4 as JSON - var vector4Value = _playroomKit.GetState("TestState"); - // Assert for Vector4 - Assert.AreEqual(new Vector4(1.0f, 2.0f, 3.0f, 4.0f), vector4Value); - _interop.Received(4).GetStateStringWrapper("TestState"); - - // Arrange & Act for Quaternion - var quaternionJson = JsonUtility.ToJson(new Quaternion(1.0f, 2.0f, 3.0f, 4.0f)); - _interop.GetStateStringWrapper("TestState").Returns(quaternionJson); // Mock for Quaternion as JSON - var quaternionValue = _playroomKit.GetState("TestState"); - // Assert for Quaternion - Assert.AreEqual(new Quaternion(1.0f, 2.0f, 3.0f, 4.0f), quaternionValue); - _interop.Received(5).GetStateStringWrapper("TestState"); -} + public void GetState_ShouldInvokeCorrectInternalFunction_ForAllTypes() + { + // Arrange & Act for int + _interop.GetStateIntWrapper("TestState").Returns(42); // Mock for int + var intValue = _playroomKit.GetState("TestState"); + // Assert for int + Assert.AreEqual(42, intValue); + _interop.Received(1).GetStateIntWrapper("TestState"); + + // Arrange & Act for float + _interop.GetStateFloatWrapper("TestState").Returns(3.14f); // Mock for float + var floatValue = _playroomKit.GetState("TestState"); + // Assert for float + Assert.AreEqual(3.14f, floatValue); + _interop.Received(1).GetStateFloatWrapper("TestState"); + + // Arrange & Act for bool + _interop.GetStateIntWrapper("TestState").Returns(1); // Mock for bool + var boolValue = _playroomKit.GetState("TestState"); + // Assert for bool + Assert.IsTrue(boolValue); + _interop.Received(2).GetStateIntWrapper("TestState"); + + // Arrange & Act for string + _interop.GetStateStringWrapper("TestState").Returns("TestValue"); // Mock for string + var stringValue = _playroomKit.GetState("TestState"); + // Assert for string + Assert.AreEqual("TestValue", stringValue); + _interop.Received(1).GetStateStringWrapper("TestState"); + + // Arrange & Act for Vector2 + var vector2Json = JsonUtility.ToJson(new Vector2(1.0f, 2.0f)); + _interop.GetStateStringWrapper("TestState").Returns(vector2Json); // Mock for Vector2 as JSON + var vector2Value = _playroomKit.GetState("TestState"); + // Assert for Vector2 + Assert.AreEqual(new Vector2(1.0f, 2.0f), vector2Value); + _interop.Received(2).GetStateStringWrapper("TestState"); + + // Arrange & Act for Vector3 + var vector3Json = JsonUtility.ToJson(new Vector3(1.0f, 2.0f, 3.0f)); + _interop.GetStateStringWrapper("TestState").Returns(vector3Json); // Mock for Vector3 as JSON + var vector3Value = _playroomKit.GetState("TestState"); + // Assert for Vector3 + Assert.AreEqual(new Vector3(1.0f, 2.0f, 3.0f), vector3Value); + _interop.Received(3).GetStateStringWrapper("TestState"); + + // Arrange & Act for Vector4 + var vector4Json = JsonUtility.ToJson(new Vector4(1.0f, 2.0f, 3.0f, 4.0f)); + _interop.GetStateStringWrapper("TestState").Returns(vector4Json); // Mock for Vector4 as JSON + var vector4Value = _playroomKit.GetState("TestState"); + // Assert for Vector4 + Assert.AreEqual(new Vector4(1.0f, 2.0f, 3.0f, 4.0f), vector4Value); + _interop.Received(4).GetStateStringWrapper("TestState"); + + // Arrange & Act for Quaternion + var quaternionJson = JsonUtility.ToJson(new Quaternion(1.0f, 2.0f, 3.0f, 4.0f)); + _interop.GetStateStringWrapper("TestState").Returns(quaternionJson); // Mock for Quaternion as JSON + var quaternionValue = _playroomKit.GetState("TestState"); + // Assert for Quaternion + Assert.AreEqual(new Quaternion(1.0f, 2.0f, 3.0f, 4.0f), quaternionValue); + _interop.Received(5).GetStateStringWrapper("TestState"); + } [Test] public void RpcRegister_ShouldInvokeInternal_WhenCalled() { - - void HandleShoot(string data, string caller) { Debug.Log($"Caller: {caller}"); @@ -294,10 +283,8 @@ void HandleShoot(string data, string caller) _playroomKit.RpcRegister("Shoot", HandleShoot, "You shot!"); _interop.Received(1).RpcRegisterWrapper("Shoot", Arg.Any>(), "You shot!"); - - } - + [Test] public void RpcCall_ShouldInvokeCallback_WhenCalled() { @@ -308,16 +295,14 @@ public void RpcCall_ShouldInvokeCallback_WhenCalled() PlayroomKit.RpcMode.ALL, Arg.Any() )) - .Do(callInfo => { + .Do(callInfo => + { var callback = callInfo.ArgAt(3); // Index 1 for onLaunch callback - callback.Invoke(); + callback.Invoke(); }); - _playroomKit.RpcCall("Shoot","data is score", PlayroomKit.RpcMode.ALL, () => - { - receivedCalled = true; - }); - + _playroomKit.RpcCall("Shoot", "data is score", PlayroomKit.RpcMode.ALL, () => { receivedCalled = true; }); + UnityEngine.Assertions.Assert.IsTrue(receivedCalled); } @@ -337,10 +322,10 @@ void Callback2(string data) } _playroomKit.WaitForState("state", Callback2); - _interop.Received(1).WaitForStateWrapper("state",Arg.Any>()); + _interop.Received(1).WaitForStateWrapper("state", Arg.Any>()); } - - + + [Test] public void WaitForPlayerState_ShouldInvokeInternal_WhenCalled() { @@ -352,7 +337,7 @@ void Callback(string data) var playerId = "1234"; var state = "state"; - _playroomKit.WaitForPlayerState(playerId,state, Callback); + _playroomKit.WaitForPlayerState(playerId, state, Callback); _interop.Received(1).WaitForPlayerStateWrapper(playerId, state, Arg.Any>()); } @@ -370,19 +355,17 @@ JSONArray CreateJsonArray(string[] array) return jsonArray; } - + // Arrange var expectedKeysJson = CreateJsonArray(new[] { "pos" }).ToString(); // Assuming CreateJsonArray is available // Act - _playroomKit.ResetStates(new[] { "pos" }, () => - { - Debug.Log("Resetting Player states from Unity, Invoking from JS!"); - }); + _playroomKit.ResetStates(new[] { "pos" }, + () => { Debug.Log("Resetting Player states from Unity, Invoking from JS!"); }); // Assert _interop.Received(1).ResetStatesWrapper( - expectedKeysJson, + expectedKeysJson, Arg.Any() // Match any Action since the exact callback function may vary ); } @@ -407,33 +390,29 @@ JSONArray CreateJsonArray(string[] array) var expectedKeysJson = CreateJsonArray(keysToExclude).ToString(); // Assuming CreateJsonArray is available // Act - _playroomKit.ResetPlayersStates(keysToExclude, () => - { - Debug.Log("Reset Player States are "); - }); + _playroomKit.ResetPlayersStates(keysToExclude, () => { Debug.Log("Reset Player States are "); }); - // Assert + // Assert _interop.Received(1).ResetPlayersStatesWrapper( expectedKeysJson, Arg.Any() // Verifying an Action was passed in, allowing flexibility ); - } - - + + [Test] public void CreateJoyStick_ShouldInvokeInteropWithCorrectJson() { // Arrange - - static string ConvertJoystickOptionsToJson(PlayroomKit.JoystickOptions options) + + static string ConvertJoystickOptionsToJson(JoystickOptions options) { JSONNode joystickOptionsJson = new JSONObject(); joystickOptionsJson["type"] = options.type; // Serialize the buttons array JSONArray buttonsArray = new JSONArray(); - foreach (PlayroomKit.ButtonOptions button in options.buttons) + foreach (ButtonOptions button in options.buttons) { JSONObject buttonJson = new JSONObject(); buttonJson["id"] = button.id; @@ -459,7 +438,7 @@ static string ConvertJoystickOptionsToJson(PlayroomKit.JoystickOptions options) } // Function to convert ButtonOptions to JSON - static JSONNode ConvertButtonOptionsToJson(PlayroomKit.ButtonOptions button) + static JSONNode ConvertButtonOptionsToJson(ButtonOptions button) { JSONObject buttonJson = new JSONObject(); buttonJson["id"] = button.id; @@ -467,24 +446,24 @@ static JSONNode ConvertButtonOptionsToJson(PlayroomKit.ButtonOptions button) buttonJson["icon"] = button.icon; return buttonJson; } - - var joystickOptions = new PlayroomKit.JoystickOptions + + var joystickOptions = new JoystickOptions { type = "dpad", buttons = new[] { - new PlayroomKit.ButtonOptions { id = "btn1", label = "Jump", icon = "jump_icon" }, - new PlayroomKit.ButtonOptions { id = "btn2", label = "Run", icon = "run_icon" } + new ButtonOptions { id = "btn1", label = "Jump", icon = "jump_icon" }, + new ButtonOptions { id = "btn2", label = "Run", icon = "run_icon" } }, - zones = new PlayroomKit.ZoneOptions + zones = new ZoneOptions { - up = new PlayroomKit.ButtonOptions { id = "up", label = "Move Up", icon = "up_icon" }, - down = new PlayroomKit.ButtonOptions { id = "down", label = "Move Down", icon = "down_icon" }, - left = new PlayroomKit.ButtonOptions { id = "left", label = "Move Left", icon = "left_icon" }, - right = new PlayroomKit.ButtonOptions { id = "right", label = "Move Right", icon = "right_icon" } + up = new ButtonOptions { id = "up", label = "Move Up", icon = "up_icon" }, + down = new ButtonOptions { id = "down", label = "Move Down", icon = "down_icon" }, + left = new ButtonOptions { id = "left", label = "Move Left", icon = "left_icon" }, + right = new ButtonOptions { id = "right", label = "Move Right", icon = "right_icon" } } }; - + // Assuming ConvertJoystickOptionsToJson is either available or mocked var expectedJsonStr = ConvertJoystickOptionsToJson(joystickOptions); @@ -508,10 +487,10 @@ public void IsRunningInBrowser_ShouldReturnCorrectPlatform() // Act & Assert bool isRunningInBrowser = PlayroomKit.IsRunningInBrowser(); - #if UNITY_WEBGL && !UNITY_EDITOR +#if UNITY_WEBGL && !UNITY_EDITOR Assert.IsTrue(isRunningInBrowser, "IsRunningInBrowser should return true when running in WebGL outside of the editor."); - #else +#else Assert.IsFalse(isRunningInBrowser, "IsRunningInBrowser should return false when not running in WebGL."); - #endif +#endif } -} +} \ No newline at end of file diff --git a/Assets/PlayroomKit/dependencies/UnityBrowserBridge/Scripts/UnityBrowserBridge.cs b/Assets/PlayroomKit/dependencies/UnityBrowserBridge/Scripts/UnityBrowserBridge.cs index 91ee1e5..31392aa 100644 --- a/Assets/PlayroomKit/dependencies/UnityBrowserBridge/Scripts/UnityBrowserBridge.cs +++ b/Assets/PlayroomKit/dependencies/UnityBrowserBridge/Scripts/UnityBrowserBridge.cs @@ -12,293 +12,401 @@ namespace UBB { - /// - /// The UnityBrowserBridge class serves as the gateway between the Unity editor and the web browser. - /// - public class UnityBrowserBridge : MonoBehaviour - { - #if UNITY_EDITOR - - /// - /// Browser selection. - /// - public enum Browser - { - Chrome, - Edge, - Firefox, - Opera, - Safari - } - - /// - /// Static singleton property to access UnityBrowserBridge instance. - /// - public static UnityBrowserBridge Instance { get; private set; } - - /// - /// Browser to be used - /// - public Browser browser = Browser.Chrome; - - /// - /// Path to directory of the web driver. Leave this empty to search the web driver in a directory on the PATH - /// variable. - /// - public string webDriverDirectory = ""; - - /// - /// Arguments that are passed along to the web driver. Does not work for Safari. - /// - public string[] browserArguments = { }; - - /// - /// Port used for the web server. - /// - public int httpServerPort = 63388; - - /// - /// index.html file served by the web server. - /// Other resources such as style sheets or images will be accessed relative to the path of this file. - /// - public TextAsset indexFile; - - /// - /// Path to JavaScript files included in the WebGL project. - /// - public List includeJavaScriptFiles = new List(); - - // HTTP server - private HttpServer httpServer = null; - - // web driver to control the browser - private IWebDriver webDriver = null; - - // messages from the browser to be forwarded to game objects - private readonly Queue> messagesWithoutValue = new Queue>(); - private readonly Queue>> messagesWithValue = new Queue>>(); - - /// - /// Indicate whether the browser is ready to execute JavaScript commands. - /// - /// True after the browser is ready and all resources have been loaded. - public bool Ready { get; set; } = false; - - // sets instance property on awake - private void Awake() - { - Instance = this; - } - - // invoked after application has been terminated - private void OnApplicationQuit() - { - // close web driver - if (webDriver != null) - { - try - { - webDriver.Quit(); - Debug.Log("Unity Browser Bridge - Web driver has been closed."); - } - catch (Exception e) - { - Debug.LogWarning("Unity Browser Bridge - Could not close web driver: " + e.Message); - } - } - - // stop web server - if (httpServer != null) - { - try - { - httpServer.Stop(); - Debug.Log("Unity Browser Bridge - HTTP server has been stopped."); - } - catch (Exception e) - { - Debug.LogWarning("Unity Browser Bridge - Could not stop http server: " + e.Message); - } - } - } - - // initializes UnityBrowserBridge on application start - public void StartUBB() - { - // create web server - httpServer = new HttpServer(httpServerPort, Path.GetDirectoryName(AssetDatabase.GetAssetPath(indexFile))); - httpServer.Start(); - - // add javascript files - foreach (string jsFile in includeJavaScriptFiles) - { - // resolve path relative to 'Assets' folder (if file exists) - if (File.Exists(Path.Combine(Application.dataPath, jsFile))) - httpServer.AddJSFile(Path.Combine(Application.dataPath, jsFile)); - else - httpServer.AddJSFile(jsFile); - } - - // initialize web driver - switch (browser) - { - case Browser.Chrome: - ChromeOptions chromeOptions = new ChromeOptions(); - chromeOptions.AddArguments(browserArguments); - webDriver = string.IsNullOrEmpty(webDriverDirectory) ? new ChromeDriver(chromeOptions) : new ChromeDriver(webDriverDirectory, chromeOptions); - break; - case Browser.Edge: - EdgeOptions edgeOptions = new EdgeOptions(); - edgeOptions.AddArguments(browserArguments); - webDriver = string.IsNullOrEmpty(webDriverDirectory) ? new EdgeDriver(edgeOptions) : new EdgeDriver(webDriverDirectory, edgeOptions); - break; - case Browser.Firefox: - FirefoxOptions firefoxOptions = new FirefoxOptions(); - firefoxOptions.AddArguments(browserArguments); - webDriver = string.IsNullOrEmpty(webDriverDirectory) ? new FirefoxDriver(firefoxOptions) : new FirefoxDriver(webDriverDirectory, firefoxOptions); - break; - case Browser.Opera: - OperaOptions operaOptions = new OperaOptions(); - operaOptions.AddArguments(browserArguments); - webDriver = string.IsNullOrEmpty(webDriverDirectory) ? new OperaDriver(operaOptions) : new OperaDriver(webDriverDirectory, operaOptions); - break; - case Browser.Safari: - SafariOptions safariOptions = new SafariOptions(); - if (browserArguments.Length > 0) - Debug.LogWarning("Unity Browser Bridge - Safari Web Driver does not allow adding generic arguments. Please configure SafariOptions directly."); - webDriver = string.IsNullOrEmpty(webDriverDirectory) ? new SafariDriver(safariOptions) : new SafariDriver(webDriverDirectory, safariOptions); - break; - } - - // open web interface - webDriver.Url = "http://localhost:" + httpServerPort + "/"; - } - - // update - private void Update() - { - // send queued messages to game objects - lock (messagesWithoutValue) - { - while (messagesWithoutValue.Count > 0) - { - KeyValuePair message = messagesWithoutValue.Dequeue(); - string gameObjectName = message.Key; - string methodName = message.Value; - GameObject go = GameObject.Find(gameObjectName); - if (go != null) - go.SendMessage(methodName); - else - Debug.LogError("Unity Browser Bridge - Could not find game object '" + gameObjectName + "'"); - } - } - - // send queued messages to game objects - lock (messagesWithValue) - { - while (messagesWithValue.Count > 0) - { - KeyValuePair> message = messagesWithValue.Dequeue(); - string gameObjectName = message.Key; - string methodName = message.Value.Key; - object value = message.Value.Value; - GameObject go = GameObject.Find(gameObjectName); - if (go != null) - go.SendMessage(methodName, value); - else - Debug.LogError("Unity Browser Bridge - Could not find game object '" + gameObjectName + "'"); - } - } - } - - /// - /// Executes JavaScript command without return value. - /// - /// JavaScript command to be executed. - public void ExecuteJS(string jsCommand) - { - if (!Ready) - { - Debug.LogError("Unity Browser Bridge - Browser is not ready"); - return; - } - - try - { - ((IJavaScriptExecutor)webDriver).ExecuteScript("_ubb_logBrowserCall('" + jsCommand.Replace("'", "'") + "')"); - ((IJavaScriptExecutor)webDriver).ExecuteScript(jsCommand); - } - catch (Exception e) - { - Debug.LogError("Unity Browser Bridge - Could not execute command " + jsCommand + ": " + e.Message); - } - } - - /// - /// Executes JavaScript command with a return value of type T. - /// - /// JavaScript command to be executed. - /// Type of return value. - /// The value returned by the given command or default(T) if the command could not be - /// executed. - public T ExecuteJS(string jsCommand) - { - // abort if browser is not ready - if (!Ready) - { - Debug.LogError("Unity Browser Bridge - Browser is not ready"); - return default; - } - - // execute command - object result; - try - { - ((IJavaScriptExecutor)webDriver).ExecuteScript("_ubb_logBrowserCall('" + jsCommand.Replace("'", "'") + "')"); - result = ((IJavaScriptExecutor)webDriver).ExecuteScript("return " + jsCommand); - } - catch (Exception e) - { - Debug.LogError("Unity Browser Bridge - Could not execute command " + jsCommand + ": " + e.Message); - return default; - } - - // convert type - try - { - return (T)Convert.ChangeType(result, typeof(T)); - } - catch (Exception) - { - Debug.LogError("Unity Browser Bridge - Could not convert return value from " + jsCommand + " to type " + typeof(T)); - return default; - } - } - - /// - /// Enqueues a message without value to be forwarded to the given game object in the next update. - /// - /// Name of the game object. - /// Method name. - public void SendMessageToGameObject(string gameObjectName, string methodName) - { - lock (messagesWithoutValue) - messagesWithoutValue.Enqueue(new KeyValuePair(gameObjectName, methodName)); - } - - - /// - /// Enqueues a message with a value to be forwarded to the given game object in the next update. - /// - /// Name of the game object. - /// Method name. - /// The value sent with the message. - public void SendMessageToGameObject(string gameObjectName, string methodName, object value) - { - lock (messagesWithValue) - messagesWithValue.Enqueue(new KeyValuePair>(gameObjectName, new KeyValuePair(methodName, value))); - } - - # endif - } + /// + /// The UnityBrowserBridge class serves as the gateway between the Unity editor and the web browser. + /// + public class UnityBrowserBridge : MonoBehaviour + { +#if UNITY_EDITOR + + /// + /// Browser selection. + /// + public enum Browser + { + Chrome, + Edge, + Firefox, + Opera, + Safari + } + + /// + /// Static singleton property to access UnityBrowserBridge instance. + /// + // public static UnityBrowserBridge Instance { get; private set; } + + /// + /// Browser to be used + /// + public Browser browser = Browser.Chrome; + + /// + /// Path to directory of the web driver. Leave this empty to search the web driver in a directory on the PATH + /// variable. + /// + public string webDriverDirectory = ""; + + /// + /// Arguments that are passed along to the web driver. Does not work for Safari. + /// + public string[] browserArguments = { }; + + /// + /// Port used for the web server. + /// + public int httpServerPort = 63388; + + /// + /// index.html file served by the web server. + /// Other resources such as style sheets or images will be accessed relative to the path of this file. + /// + public TextAsset indexFile; + + /// + /// Path to JavaScript files included in the WebGL project. + /// + public List includeJavaScriptFiles = new List(); + + // HTTP server + private HttpServer httpServer = null; + + // web driver to control the browser + private IWebDriver webDriver = null; + + // messages from the browser to be forwarded to game objects + private readonly Queue> messagesWithoutValue = + new Queue>(); + private readonly Queue>> messagesWithValue = + new Queue>>(); + + /// + /// Indicate whether the browser is ready to execute JavaScript commands. + /// + /// True after the browser is ready and all resources have been loaded. + public bool Ready { get; set; } = false; + + private static readonly Dictionary GameObjectReferences = new(); + + // Create a singleton instance, called from InsertCoin + private static UnityBrowserBridge _instance; + public static UnityBrowserBridge Instance + { + get + { + if (_instance == null) + { + CreateInstance(); + } + + return _instance; + } + private set => _instance = value; + } + + public static void CreateInstance() + { + if (_instance == null) + { + _instance = FindObjectOfType(); + if (_instance == null) + { + Debug.LogError( + "No UnityBrowserBridge component found in the scene. Please ensure it is attached to a GameObject."); + return; + } + } + } + + // invoked after application has been terminated + private void OnApplicationQuit() + { + // close web driver + if (webDriver != null) + { + try + { + webDriver.Quit(); + Debug.Log("Unity Browser Bridge - Web driver has been closed."); + } + catch (Exception e) + { + Debug.LogWarning("Unity Browser Bridge - Could not close web driver: " + e.Message); + } + } + + // stop web server + if (httpServer != null) + { + try + { + httpServer.Stop(); + Debug.Log("Unity Browser Bridge - HTTP server has been stopped."); + } + catch (Exception e) + { + Debug.LogWarning("Unity Browser Bridge - Could not stop http server: " + e.Message); + } + } + } + + // initializes UnityBrowserBridge on application start + public void StartUBB() + { + // create web server + httpServer = new HttpServer(httpServerPort, Path.GetDirectoryName(AssetDatabase.GetAssetPath(indexFile))); + httpServer.Start(); + + // add javascript files + foreach (string jsFile in includeJavaScriptFiles) + { + // resolve path relative to 'Assets' folder (if file exists) + if (File.Exists(Path.Combine(Application.dataPath, jsFile))) + httpServer.AddJSFile(Path.Combine(Application.dataPath, jsFile)); + else + httpServer.AddJSFile(jsFile); + } + + // initialize web driver + switch (browser) + { + case Browser.Chrome: + ChromeOptions chromeOptions = new ChromeOptions(); + chromeOptions.AddArguments(browserArguments); + webDriver = string.IsNullOrEmpty(webDriverDirectory) + ? new ChromeDriver(chromeOptions) + : new ChromeDriver(webDriverDirectory, chromeOptions); + break; + case Browser.Edge: + EdgeOptions edgeOptions = new EdgeOptions(); + edgeOptions.AddArguments(browserArguments); + webDriver = string.IsNullOrEmpty(webDriverDirectory) + ? new EdgeDriver(edgeOptions) + : new EdgeDriver(webDriverDirectory, edgeOptions); + break; + case Browser.Firefox: + FirefoxOptions firefoxOptions = new FirefoxOptions(); + firefoxOptions.AddArguments(browserArguments); + webDriver = string.IsNullOrEmpty(webDriverDirectory) + ? new FirefoxDriver(firefoxOptions) + : new FirefoxDriver(webDriverDirectory, firefoxOptions); + break; + case Browser.Opera: + OperaOptions operaOptions = new OperaOptions(); + operaOptions.AddArguments(browserArguments); + webDriver = string.IsNullOrEmpty(webDriverDirectory) + ? new OperaDriver(operaOptions) + : new OperaDriver(webDriverDirectory, operaOptions); + break; + case Browser.Safari: + SafariOptions safariOptions = new SafariOptions(); + if (browserArguments.Length > 0) + Debug.LogWarning( + "Unity Browser Bridge - Safari Web Driver does not allow adding generic arguments. Please configure SafariOptions directly."); + webDriver = string.IsNullOrEmpty(webDriverDirectory) + ? new SafariDriver(safariOptions) + : new SafariDriver(webDriverDirectory, safariOptions); + break; + } + + // open web interface + webDriver.Url = "http://localhost:" + httpServerPort + "/"; + } + + // update + private void Update() + { + // send queued messages to game objects + lock (messagesWithoutValue) + { + while (messagesWithoutValue.Count > 0) + { + KeyValuePair message = messagesWithoutValue.Dequeue(); + string gameObjectName = message.Key; + string methodName = message.Value; + GameObject go = GameObject.Find(gameObjectName); + if (go != null) + go.SendMessage(methodName); + else + Debug.LogError("Unity Browser Bridge - Could not find game object '" + gameObjectName + "'"); + } + } + + // send queued messages to game objects + lock (messagesWithValue) + { + while (messagesWithValue.Count > 0) + { + KeyValuePair> message = messagesWithValue.Dequeue(); + string gameObjectName = message.Key; + string methodName = message.Value.Key; + object value = message.Value.Value; + GameObject go = GameObject.Find(gameObjectName); + if (go != null) + go.SendMessage(methodName, value); + else + Debug.LogError("Unity Browser Bridge - Could not find game object '" + gameObjectName + "'"); + } + } + } + + /// + /// Executes JavaScript command without return value. + /// + /// JavaScript command to be executed. + public void ExecuteJS(string jsCommand) + { + if (!Ready) + { + Debug.LogError("Unity Browser Bridge - Browser is not ready"); + return; + } + + try + { + ((IJavaScriptExecutor)webDriver).ExecuteScript("_ubb_logBrowserCall('" + + jsCommand.Replace("'", "'") + "')"); + ((IJavaScriptExecutor)webDriver).ExecuteScript(jsCommand); + } + catch (Exception e) + { + Debug.LogError( + "Unity Browser Bridge - Could not execute command " + jsCommand + ": " + e.Message); + } + } + + /// + /// Executes JavaScript command with a return value of type T. + /// + /// JavaScript command to be executed. + /// Type of return value. + /// The value returned by the given command or default(T) if the command could not be + /// executed. + public T ExecuteJS(string jsCommand) + { + // abort if browser is not ready + if (!Ready) + { + Debug.LogError("Unity Browser Bridge - Browser is not ready"); + return default; + } + + // execute command + object result; + try + { + ((IJavaScriptExecutor)webDriver).ExecuteScript("_ubb_logBrowserCall('" + + jsCommand.Replace("'", "'") + "')"); + result = ((IJavaScriptExecutor)webDriver).ExecuteScript("return " + jsCommand); + } + catch (Exception e) + { + Debug.LogError( + "Unity Browser Bridge - Could not execute command " + jsCommand + ": " + e.Message); + return default; + } + + // convert type + try + { + return (T)Convert.ChangeType(result, typeof(T)); + } + catch (Exception) + { + Debug.LogError("Unity Browser Bridge - Could not convert return value from " + jsCommand + + " to type " + typeof(T)); + return default; + } + } + + /// + /// Enqueues a message without value to be forwarded to the given game object in the next update. + /// + /// Name of the game object. + /// Method name. + public void SendMessageToGameObject(string gameObjectName, string methodName) + { + lock (messagesWithoutValue) + messagesWithoutValue.Enqueue(new KeyValuePair(gameObjectName, methodName)); + } + + + /// + /// Enqueues a message with a value to be forwarded to the given game object in the next update. + /// + /// Name of the game object. + /// Method name. + /// The value sent with the message. + public void SendMessageToGameObject(string gameObjectName, string methodName, object value) + { + lock (messagesWithValue) + messagesWithValue.Enqueue(new KeyValuePair>(gameObjectName, + new KeyValuePair(methodName, value))); + } + + public void RegisterGameObject(string key, GameObject gameObject) + { + if (!GameObjectReferences.ContainsKey(key)) + GameObjectReferences.Add(key, gameObject); + else + GameObjectReferences[key] = gameObject; + } + + public GameObject GetGameObject(string key) + { + GameObjectReferences.TryGetValue(key, out var gameObject); + return gameObject; + } + + public void CallJs(string jsFunctionName, string callbackName = null, string gameObjectName = null, + bool isAsync = false, params string[] args) + { + List allParams = new(); + + Debug.LogWarning(args); + + foreach (var param in args) + { + if (param.StartsWith("{") && param.EndsWith("}")) + allParams.Add(param); + else + allParams.Add($"'{param}'"); + } + + if (!string.IsNullOrEmpty(callbackName)) allParams.Add($"'{callbackName}'"); + if (!string.IsNullOrEmpty(gameObjectName)) allParams.Add($"'{gameObjectName}'"); + + string jsCall = $"{jsFunctionName}({string.Join(", ", allParams)})"; + if (isAsync) jsCall = $"await {jsCall}"; + + + Debug.Log(jsCall); + ExecuteJS(jsCall); + } + + + public T CallJs(string jsFunctionName, string callbackName = null, string gameObjectName = null, + bool isAsync = false, params string[] args) + { + List allParams = new(); + foreach (string param in args) + { + if (param.StartsWith("{") && param.EndsWith("}")) + allParams.Add(param); + else + allParams.Add($"'{param}'"); + } + + if (!string.IsNullOrEmpty(callbackName)) allParams.Add($"'{callbackName}'"); + if (!string.IsNullOrEmpty(gameObjectName)) allParams.Add($"'{gameObjectName}'"); + + string jsCall = $"{jsFunctionName}({string.Join(", ", allParams)})"; + if (isAsync) jsCall = $"await {jsCall}"; + + Debug.Log(jsCall); + return ExecuteJS(jsCall); + } + +# endif + } } \ No newline at end of file diff --git a/Assets/PlayroomKit/modules/Helpers/Helpers.cs b/Assets/PlayroomKit/modules/Helpers/Helpers.cs index 53b0f0e..57ab29a 100644 --- a/Assets/PlayroomKit/modules/Helpers/Helpers.cs +++ b/Assets/PlayroomKit/modules/Helpers/Helpers.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using SimpleJSON; using UnityEngine; @@ -8,9 +7,9 @@ namespace Playroom /// /// This file contains functions, mostly used for serialization / deserialization /// - public partial class PlayroomKit + public class Helpers { - private static string SerializeInitOptions(InitOptions options) + public static string SerializeInitOptions(InitOptions options) { if (options == null) return null; @@ -109,7 +108,7 @@ private static JSONNode ConvertValueToJSON(object value) } } - private static JSONArray CreateJsonArray(string[] array) + public static JSONArray CreateJsonArray(string[] array) { JSONArray jsonArray = new JSONArray(); @@ -120,40 +119,8 @@ private static JSONArray CreateJsonArray(string[] array) return jsonArray; } - - public class JoystickOptions - { - public string type = "angular"; // default = angular, can be dpad - - public ButtonOptions[] buttons; - public ZoneOptions zones = null; - } - - [Serializable] - public class ButtonOptions - { - public string id = null; - public string label = ""; - public string icon = null; - } - - public class ZoneOptions - { - public ButtonOptions up = null; - public ButtonOptions down = null; - public ButtonOptions left = null; - public ButtonOptions right = null; - } - - - [Serializable] - public class Dpad - { - public string x; - public string y; - } - private static string ConvertJoystickOptionsToJson(JoystickOptions options) + public static string ConvertJoystickOptionsToJson(JoystickOptions options) { JSONNode joystickOptionsJson = new JSONObject(); joystickOptionsJson["type"] = options.type; @@ -195,11 +162,11 @@ private static JSONNode ConvertButtonOptionsToJson(ButtonOptions button) return buttonJson; } - private static Player.Profile ParseProfile(string json) + public static PlayroomKit.Player.Profile ParseProfile(string json) { var jsonNode = JSON.Parse(json); - var profileData = new Player.Profile(); - profileData.playerProfileColor = new Player.Profile.PlayerProfileColor + var profileData = new PlayroomKit.Player.Profile(); + profileData.playerProfileColor = new PlayroomKit.Player.Profile.PlayerProfileColor { r = jsonNode["color"]["r"].AsInt, g = jsonNode["color"]["g"].AsInt, @@ -240,7 +207,5 @@ private static Dictionary ParseJsonToDictionary(string jsonString) return dictionary; } - - } } \ No newline at end of file diff --git a/Assets/PlayroomKit/modules/Interfaces/IPlayerBase.cs b/Assets/PlayroomKit/modules/Interfaces/IPlayerBase.cs index 5519987..9488b27 100644 --- a/Assets/PlayroomKit/modules/Interfaces/IPlayerBase.cs +++ b/Assets/PlayroomKit/modules/Interfaces/IPlayerBase.cs @@ -20,10 +20,9 @@ public interface IPlayerBase public void Kick(Action onKickCallBack = null); public void WaitForState(string stateKey, Action onStateSetCallback = null); - - protected static Action onKickCallBack = null; + protected static Action onKickCallBack = null; } } } -} +} \ No newline at end of file diff --git a/Assets/PlayroomKit/modules/Interfaces/IPlayroomBase.cs b/Assets/PlayroomKit/modules/Interfaces/IPlayroomBase.cs index 53d3c09..0083c57 100644 --- a/Assets/PlayroomKit/modules/Interfaces/IPlayroomBase.cs +++ b/Assets/PlayroomKit/modules/Interfaces/IPlayroomBase.cs @@ -38,9 +38,9 @@ public void InsertCoin(InitOptions options = null, Action onLaunchCallBack = nul public void WaitForPlayerState(string playerID, string stateKey, Action onStateSetCallback = null); - public void ResetStates(string[] keysToExclude = null, Action OnStatesReset = null); + public void ResetStates(string[] keysToExclude = null, Action onStatesReset = null); - public void ResetPlayersStates(string[] keysToExclude = null, Action OnStatesReset = null); + public void ResetPlayersStates(string[] keysToExclude = null, Action onStatesReset = null); public void CreateJoyStick(JoystickOptions options); @@ -56,7 +56,7 @@ protected static void __OnPlayerJoinCallbackHandler(string id) protected static void OnPlayerJoinWrapperCallback(string id) { - var player = GetPlayer(id); + var player = GetPlayerById(id); foreach (var callback in IPlayroomBase.OnPlayerJoinCallbacks) { callback?.Invoke(player); diff --git a/Assets/PlayroomKit/modules/Interfaces/IRPC.cs b/Assets/PlayroomKit/modules/Interfaces/IRPC.cs index 4095eb5..788a811 100644 --- a/Assets/PlayroomKit/modules/Interfaces/IRPC.cs +++ b/Assets/PlayroomKit/modules/Interfaces/IRPC.cs @@ -16,9 +16,9 @@ public enum RpcMode OTHERS, HOST } + public interface IRPC { - protected static List rpcCalledEvents = new(); protected static Dictionary> OnResponseCallbacks = @@ -146,12 +146,12 @@ protected static void InvokeRpcRegisterCallBack(string dataJson, string senderJs List updatedRpcCalledEvents = new(); // This state is required to update the called rpc events list, (Temp fix see RpcCall for more) - + //Fix this later PlayroomKit _playroomKit = new PlayroomKit(); string nameJson = _playroomKit.GetState("rpcCalledEventName"); // - + Debug.Log($"rpcCalledEventName {nameJson}: {dataJson}"); JSONArray jsonArray = JSON.Parse(nameJson).AsArray; diff --git a/Assets/PlayroomKit/modules/MockMode/BrowserMode/BrowserMockPlayerService.cs b/Assets/PlayroomKit/modules/MockMode/BrowserMode/BrowserMockPlayerService.cs new file mode 100644 index 0000000..c37e187 --- /dev/null +++ b/Assets/PlayroomKit/modules/MockMode/BrowserMode/BrowserMockPlayerService.cs @@ -0,0 +1,135 @@ +using System; +using UBB; +using UnityEngine; + +namespace Playroom +{ + public class BrowserMockPlayerService : PlayroomKit.Player.IPlayerBase + { + private readonly UnityBrowserBridge _ubb; + private string _id; + + public BrowserMockPlayerService(UnityBrowserBridge ubb, string id) + { + _ubb = ubb; + _id = id; + } + + #region State + + public void SetState(string key, int value, bool reliable = false) + { + _ubb.CallJs("SetPlayerStateByPlayerId", null, null, false, _id, key, value.ToString(), + reliable.ToString().ToLower()); + } + + public void SetState(string key, float value, bool reliable = false) + { + _ubb.CallJs("SetPlayerStateByPlayerId", null, null, false, _id, key, value.ToString(), + reliable.ToString().ToLower()); + } + + public void SetState(string key, bool value, bool reliable = false) + { + _ubb.CallJs("SetPlayerStateByPlayerId", null, null, false, _id, key, value.ToString(), + reliable.ToString().ToLower()); + } + + public void SetState(string key, string value, bool reliable = false) + { + _ubb.CallJs("SetPlayerStateByPlayerId", null, null, false, _id, key, value.ToString(), + reliable.ToString().ToLower()); + } + + public void SetState(string key, object value, bool reliable = false) + { + string json; + + // Check if the value is a primitive type and wrap it if necessary + json = JsonUtility.ToJson(value is int or float or bool or string + ? new PrimitiveWrapper(value) + : value); + + _ubb.CallJs("SetPlayerStateByPlayerId", null, null, false, _id, key, json, + reliable.ToString().ToLower()); + } + + public T GetState(string key) + { + string stringValue = _ubb.CallJs("GetPlayerStateByPlayerId", null, null, false, _id, key); + + if (string.IsNullOrEmpty(stringValue)) + { + Debug.LogWarning($"State for key '{key}' is null or empty."); + return default; + } + + try + { + if (typeof(T) == typeof(int) || typeof(T) == typeof(float) || typeof(T) == typeof(bool) || + typeof(T) == typeof(string)) + { + var wrapper = JsonUtility.FromJson>(stringValue); + return wrapper.value; + } + else + { + return JsonUtility.FromJson(stringValue); + } + } + catch (Exception e) + { + Debug.LogError($"Failed to parse JSON for key '{key}': {e.Message}"); + return default; // Return default if parsing fails. + } + } + + #endregion + + public PlayroomKit.Player.Profile GetProfile() + { + string json = _ubb.CallJs("GetProfile", null, null, false, _id); + + Debug.Log(json); + + var profileData = Helpers.ParseProfile(json); + return profileData; + } + + public Action OnQuit(Action callback) + { + Debug.LogWarning("OnQuit not supported yet in Browser Mode"); + return default; + } + + public void Kick(Action onKickCallBack = null) + { + _ubb.CallJs("Kick", null, null, true, _id); + } + + public void WaitForState(string stateKey, Action onStateSetCallback = null) + { + string callbackKey = $"WaitForState_{stateKey}"; + GameObject callbackObject = new GameObject(callbackKey); + Debug.Log(callbackKey); + + MockCallbackInvoker invoker = callbackObject.AddComponent(); + invoker.SetCallback(onStateSetCallback, callbackKey); + CallBacksHandlerMock.Instance.RegisterCallbackObject(callbackKey, callbackObject, "ExecuteCallback"); + + _ubb.CallJs("WaitForPlayerState", null, null, true, _id, stateKey, callbackKey); + } + + + #region UTILS + + [Serializable] + private class PrimitiveWrapper + { + public T value; + public PrimitiveWrapper(T value) => this.value = value; + } + + #endregion + } +} \ No newline at end of file diff --git a/Assets/PlayroomKit/modules/MockMode/BrowserMode/BrowserMockPlayerService.cs.meta b/Assets/PlayroomKit/modules/MockMode/BrowserMode/BrowserMockPlayerService.cs.meta new file mode 100644 index 0000000..0c1d026 --- /dev/null +++ b/Assets/PlayroomKit/modules/MockMode/BrowserMode/BrowserMockPlayerService.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: a57950c9f0dd42cdb4e52d6f6d92d115 +timeCreated: 1731500261 \ No newline at end of file diff --git a/Assets/PlayroomKit/modules/MockMode/BrowserMode/BrowserMockRPC.cs b/Assets/PlayroomKit/modules/MockMode/BrowserMode/BrowserMockRPC.cs new file mode 100644 index 0000000..d314a95 --- /dev/null +++ b/Assets/PlayroomKit/modules/MockMode/BrowserMode/BrowserMockRPC.cs @@ -0,0 +1,34 @@ +#if UNITY_EDITOR +using System; +using UBB; +using UnityEngine; + +namespace Playroom +{ + public class BrowserMockRPC : PlayroomKit.IRPC + { + public void RpcRegister(string name, Action rpcRegisterCallback, string onResponseReturn = null) + { + string callbackKey = $"RpcEvent_{name}"; + GameObject callbackObject = new GameObject(callbackKey); + Debug.Log(callbackKey); + + MockCallbackInvoker invoker = callbackObject.AddComponent(); + invoker.SetCallback(rpcRegisterCallback, callbackKey); + CallBacksHandlerMock.Instance.RegisterCallbackObject(callbackKey, callbackObject, "ExecuteCallback"); + + UnityBrowserBridge.Instance.CallJs("RpcRegister", null, null, false, name, callbackKey, onResponseReturn); + } + + public void RpcCall(string name, object data, PlayroomKit.RpcMode mode, Action callbackOnResponse = null) + { + UnityBrowserBridge.Instance.CallJs("RpcCall", null, null, false, name, data.ToString(), mode.ToString()); + } + + public void RpcCall(string name, object data, Action callbackOnResponse = null) + { + RpcCall(name, data, PlayroomKit.RpcMode.ALL, callbackOnResponse); + } + } +} +#endif \ No newline at end of file diff --git a/Assets/PlayroomKit/modules/MockMode/BrowserMode/BrowserMockRPC.cs.meta b/Assets/PlayroomKit/modules/MockMode/BrowserMode/BrowserMockRPC.cs.meta new file mode 100644 index 0000000..10830ef --- /dev/null +++ b/Assets/PlayroomKit/modules/MockMode/BrowserMode/BrowserMockRPC.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 1eac67bc5fe34e69b0faf7731d141ba8 +timeCreated: 1731681415 \ No newline at end of file diff --git a/Assets/PlayroomKit/modules/MockMode/BrowserMode/BrowserMockService.cs b/Assets/PlayroomKit/modules/MockMode/BrowserMode/BrowserMockService.cs new file mode 100644 index 0000000..65b2dee --- /dev/null +++ b/Assets/PlayroomKit/modules/MockMode/BrowserMode/BrowserMockService.cs @@ -0,0 +1,195 @@ +using System; +using System.Reflection; +using UBB; +using UnityEngine; +using ParrelSync; + +namespace Playroom +{ +#if UNITY_EDITOR + public class BrowserMockService : PlayroomKit.IPlayroomBase + { + private UnityBrowserBridge _ubb; + + #region Initialization Methods + + public void InsertCoin(InitOptions options = null, Action onLaunchCallBack = null, + Action onDisconnectCallback = null) + { + // start ubb before inserting coin + _ubb = UnityBrowserBridge.Instance; + if (ClonesManager.IsClone()) + { + _ubb.httpServerPort += 10; + } + _ubb.StartUBB(); + + string optionsJson = null; + if (options != null) + { + options.roomCode = "TEST_ROOM"; + optionsJson = Helpers.SerializeInitOptions(options); + } + + var gameObjectName = _ubb.GetGameObject("InsertCoin").name; + _ubb.CallJs("InsertCoin", onLaunchCallBack.GetMethodInfo().Name, gameObjectName, true, optionsJson); + PlayroomKit.IsPlayRoomInitialized = true; + } + + public Action OnPlayerJoin(Action onPlayerJoinCallback) + { + if (!PlayroomKit.IPlayroomBase.OnPlayerJoinCallbacks.Contains(onPlayerJoinCallback)) + PlayroomKit.IPlayroomBase.OnPlayerJoinCallbacks.Add(onPlayerJoinCallback); + + _ubb.CallJs("OnPlayerJoin", null, _ubb.GetGameObject("devManager").name); + + void Unsub() + { + Debug.Log("Unsubscribing from OnPlayerJoin"); + } + + return Unsub; + } + + public void StartMatchmaking(Action callback = null) + { + _ubb.CallJs("StartMatchmaking", null, null, true); + callback?.Invoke(); + } + + public void OnDisconnect(Action callback) + { + string key = Guid.NewGuid().ToString(); + string callbackKey = $"OnDisconnect_{key}"; + GameObject callbackObject = new GameObject(callbackKey); + MockCallbackInvoker invoker = callbackObject.AddComponent(); + invoker.SetCallback(callback, callbackKey); + _ubb.CallJs("OnDisconnect", callbackKey); + } + + #endregion + + #region Local Player Mehtods + + public PlayroomKit.Player MyPlayer() + { + string id = _ubb.CallJs("MyPlayer"); + return PlayroomKit.GetPlayerById(id); + } + + public PlayroomKit.Player Me() + { + return MyPlayer(); + } + + #endregion + + #region Room Mehtods + + public bool IsHost() + { + return _ubb.CallJs("IsHost"); + } + + public string GetRoomCode() + { + return _ubb.CallJs("GetRoomCode"); + } + + public bool IsStreamScreen() + { + return _ubb.CallJs("IsStreamScreen"); + } + + #endregion + + #region State Syncing Methods + + public void SetState(string key, T value, bool reliable = false) + { + _ubb.CallJs("SetState", null, null, true, + key, value.ToString(), reliable.ToString().ToLower()); + } + + public T GetState(string key) + { + return _ubb.CallJs("GetState", null, null, false, key); + } + + public void WaitForState(string stateKey, Action onStateSetCallback = null) + { + string callbackKey = $"WaitForState_{stateKey}"; + GameObject callbackObject = new GameObject(callbackKey); + + MockCallbackInvoker invoker = callbackObject.AddComponent(); + invoker.SetCallback(onStateSetCallback, callbackKey); + + CallBacksHandlerMock.Instance.RegisterCallbackObject(callbackKey, callbackObject, "ExecuteCallback"); + + _ubb.CallJs("WaitForState", null, null, true, stateKey, callbackKey); + } + + public void WaitForPlayerState(string playerID, string stateKey, Action onStateSetCallback = null) + { + string callbackKey = $"WaitForPlayerState_{stateKey}"; + GameObject callbackObject = new GameObject(callbackKey); + MockCallbackInvoker invoker = callbackObject.AddComponent(); + + invoker.SetCallback(onStateSetCallback, callbackKey); + CallBacksHandlerMock.Instance.RegisterCallbackObject(callbackKey, callbackObject, "ExecuteCallback"); + + _ubb.CallJs("WaitForPlayerState", callbackKey, null, false, playerID, stateKey); + } + + public void ResetStates(string[] keysToExclude = null, Action onStatesReset = null) + { + _ubb.CallJs("ResetStates", null, null, true, keysToExclude ?? Array.Empty()); + onStatesReset?.Invoke(); + } + + public void ResetPlayersStates(string[] keysToExclude = null, Action onStatesReset = null) + { + _ubb.CallJs("ResetPlayersStates", null, null, true, keysToExclude ?? Array.Empty()); + onStatesReset?.Invoke(); + } + + #endregion + + #region Misc + + // TODO: will implement after Player is implemented. + public void UnsubscribeOnQuit() + { + throw new NotImplementedException(); + } + + #endregion + + #region Joystick Mehtods + + public void CreateJoyStick(JoystickOptions options) + { + Debug.LogWarning("Create Joystick is not supported in mock mode!"); + } + + public Dpad DpadJoystick() + { + Debug.LogWarning("Dpad Joystick is not supported in mock mode!"); + return null; + } + + #endregion + + #region Utils + + public static void MockOnPlayerJoinWrapper(string playerId) + { + PlayroomKit.IPlayroomBase.OnPlayerJoinWrapperCallback(playerId); + } + + #endregion + } + + +#endif +} \ No newline at end of file diff --git a/Assets/PlayroomKit/modules/MockMode/BrowserMode/BrowserMockService.cs.meta b/Assets/PlayroomKit/modules/MockMode/BrowserMode/BrowserMockService.cs.meta new file mode 100644 index 0000000..eec7510 --- /dev/null +++ b/Assets/PlayroomKit/modules/MockMode/BrowserMode/BrowserMockService.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 60828dd9182b4585968750ea74aa526d +timeCreated: 1731309967 \ No newline at end of file diff --git a/Assets/PlayroomKit/modules/MockMode/BrowserMode/MockModeBrowser.cs b/Assets/PlayroomKit/modules/MockMode/BrowserMode/MockModeBrowser_old.cs similarity index 95% rename from Assets/PlayroomKit/modules/MockMode/BrowserMode/MockModeBrowser.cs rename to Assets/PlayroomKit/modules/MockMode/BrowserMode/MockModeBrowser_old.cs index 7aaa8b0..67fc023 100644 --- a/Assets/PlayroomKit/modules/MockMode/BrowserMode/MockModeBrowser.cs +++ b/Assets/PlayroomKit/modules/MockMode/BrowserMode/MockModeBrowser_old.cs @@ -7,6 +7,7 @@ using UnityEngine.Networking; using Random = System.Random; + namespace Playroom { /// @@ -34,12 +35,12 @@ public static GameObject GetGameObject(string key) private static void MockInsertCoinBrowser(InitOptions options, Action onLaunchCallBack) { - isPlayRoomInitialized = true; + IsPlayRoomInitialized = true; Debug.Log("Coin Inserted!"); string optionsJson = null; - if (options != null) optionsJson = SerializeInitOptions(options); + if (options != null) optionsJson = Helpers.SerializeInitOptions(options); #if UNITY_EDITOR var gameObjectName = GetGameObject("InsertCoin").name; @@ -71,13 +72,13 @@ private static void MockOnPlayerJoinBrowser(Action onPlayerJoinCallback) // #endif // } // -// private static void MockOnPlayerQuitLocal(Action onPlayerQuitCallback) -// { -// Debug.Log("On Player Quit"); -// var testPlayer = GetPlayer(PlayerId); -// testPlayer.OnQuitCallbacks.Add(onPlayerQuitCallback); -// __OnQuitInternalHandler(PlayerId); -// } + // private static void MockOnPlayerQuitLocal(Action onPlayerQuitCallback) + // { + // Debug.Log("On Player Quit"); + // var testPlayer = GetPlayer(PlayerId); + // testPlayer.OnQuitCallbacks.Add(onPlayerQuitCallback); + // __OnQuitInternalHandler(PlayerId); + // } /// /// This function is used by GetPlayerID in PlayroomKitDevManager, GetPlayer is only invoked @@ -232,7 +233,7 @@ private static Player MockMyPlayerBrowser() { #if UNITY_EDITOR var id = UnityBrowserBridge.Instance.ExecuteJS($"MyPlayer()"); - return GetPlayer(id); + return GetPlayerById(id); #else return default; #endif @@ -260,7 +261,7 @@ private static Player.Profile MockGetProfileBrowser(string playerID) { #if UNITY_EDITOR string json = UnityBrowserBridge.Instance.ExecuteJS($"GetProfile('{playerID}')"); - var profileData = ParseProfile(json); + var profileData = Helpers.ParseProfile(json); return profileData; #else return default; @@ -304,14 +305,10 @@ private static void MockOnDisconnectBrowser(Action callback) { #if UNITY_EDITOR string key = Guid.NewGuid().ToString(); - string callbackKey = $"OnDisconnect_{key}"; GameObject callbackObject = new GameObject(callbackKey); - MockCallbackInvoker invoker = callbackObject.AddComponent(); invoker.SetCallback(callback, callbackKey); - - UnityBrowserBridge.Instance.ExecuteJS( $"OnDisconnect('{callbackKey}')"); #endif diff --git a/Assets/PlayroomKit/modules/MockMode/BrowserMode/MockModeBrowser.cs.meta b/Assets/PlayroomKit/modules/MockMode/BrowserMode/MockModeBrowser_old.cs.meta similarity index 100% rename from Assets/PlayroomKit/modules/MockMode/BrowserMode/MockModeBrowser.cs.meta rename to Assets/PlayroomKit/modules/MockMode/BrowserMode/MockModeBrowser_old.cs.meta diff --git a/Assets/PlayroomKit/modules/MockMode/BrowserMode/PlayroomMockBridge.js b/Assets/PlayroomKit/modules/MockMode/BrowserMode/PlayroomMockBrowserBridge.js similarity index 95% rename from Assets/PlayroomKit/modules/MockMode/BrowserMode/PlayroomMockBridge.js rename to Assets/PlayroomKit/modules/MockMode/BrowserMode/PlayroomMockBrowserBridge.js index 66a013b..54fdd81 100644 --- a/Assets/PlayroomKit/modules/MockMode/BrowserMode/PlayroomMockBridge.js +++ b/Assets/PlayroomKit/modules/MockMode/BrowserMode/PlayroomMockBrowserBridge.js @@ -15,7 +15,6 @@ OnPlayerJoin = function (gameObjectName) { // States SetState = function (key, value, reliable) { reliable = !!reliable; - Playroom.setState(key, value, reliable); }; @@ -146,7 +145,6 @@ WaitForState = function (stateKey, callbackKey) { }; const jsonData = JSON.stringify(data); - unityInstance.SendMessage("CallbackManager", "InvokeCallback", jsonData); }) .catch((error) => { @@ -176,7 +174,15 @@ WaitForPlayerState = async function (playerId, stateKey, onStateSetCallback) { return null; } - await Playroom.waitForPlayerState(playerState, stateKey, onStateSetCallback); + Playroom.waitForPlayerState(playerState, stateKey).then((stateVal) => { + const data = { + key: onStateSetCallback, + parameter: stateVal, + }; + + const jsonData = JSON.stringify(data); + unityInstance.SendMessage("CallbackManager", "InvokeCallback", jsonData); + }); }; Kick = async function (playerID) { @@ -240,7 +246,6 @@ ResetStates = async function (keysToExclude) { }; RpcRegister = function (name, callbackKey) { - console.log(name); Playroom.RPC.register(name, (data, caller) => { const jsonData = { diff --git a/Assets/PlayroomKit/modules/MockMode/BrowserMode/PlayroomMockBridge.js.meta b/Assets/PlayroomKit/modules/MockMode/BrowserMode/PlayroomMockBrowserBridge.js.meta similarity index 100% rename from Assets/PlayroomKit/modules/MockMode/BrowserMode/PlayroomMockBridge.js.meta rename to Assets/PlayroomKit/modules/MockMode/BrowserMode/PlayroomMockBrowserBridge.js.meta diff --git a/Assets/PlayroomKit/modules/MockMode/CallBacksManagerMock.cs b/Assets/PlayroomKit/modules/MockMode/CallBacksHandlerMock.cs similarity index 94% rename from Assets/PlayroomKit/modules/MockMode/CallBacksManagerMock.cs rename to Assets/PlayroomKit/modules/MockMode/CallBacksHandlerMock.cs index 135fe98..226c69d 100644 --- a/Assets/PlayroomKit/modules/MockMode/CallBacksManagerMock.cs +++ b/Assets/PlayroomKit/modules/MockMode/CallBacksHandlerMock.cs @@ -7,6 +7,11 @@ namespace Playroom { public class CallBacksHandlerMock : MonoBehaviour { + private readonly Dictionary callbacks = new(); + + [SerializeField] + private PlayroomkitDevManager manager; + private static CallBacksHandlerMock _instance; public static CallBacksHandlerMock Instance @@ -30,25 +35,20 @@ public static CallBacksHandlerMock Instance private void Start() { - var manager = FindObjectOfType(); gameObject.transform.SetParent(manager.gameObject.transform); } - private Dictionary callbacks = new(); public void RegisterCallbackObject(string key, GameObject gameObject, string methodName) { if (!callbacks.ContainsKey(key)) { - callbacks.TryAdd(key, (gameObject, methodName)); } } public void HandleRPC(string jsonData) { - - var jsonNode = JSON.Parse(jsonData); string key = jsonNode["key"]; @@ -73,8 +73,6 @@ public void HandleRPC(string jsonData) public void InvokeCallback(string jsonData) { - - var jsonNode = JSON.Parse(jsonData); string key = jsonNode["key"]; diff --git a/Assets/PlayroomKit/modules/MockMode/CallBacksManagerMock.cs.meta b/Assets/PlayroomKit/modules/MockMode/CallBacksHandlerMock.cs.meta similarity index 100% rename from Assets/PlayroomKit/modules/MockMode/CallBacksManagerMock.cs.meta rename to Assets/PlayroomKit/modules/MockMode/CallBacksHandlerMock.cs.meta diff --git a/Assets/PlayroomKit/modules/MockMode/LocalPlayroomService.cs b/Assets/PlayroomKit/modules/MockMode/LocalPlayroomService.cs index 1d4f489..65194c8 100644 --- a/Assets/PlayroomKit/modules/MockMode/LocalPlayroomService.cs +++ b/Assets/PlayroomKit/modules/MockMode/LocalPlayroomService.cs @@ -5,166 +5,158 @@ namespace Playroom { - public partial class PlayroomKit + public class LocalMockPlayroomService : PlayroomKit.IPlayroomBase { - public class LocalMockPlayroomService : IPlayroomBase - { - private Dictionary mockGlobalStates = new(); - - // private Dictionary> stateCallbacks = new(); + private Dictionary mockGlobalStates = new(); + private const string PlayerId = "mockplayerID123"; - private const string PlayerId = "mockplayerID123"; + private static bool mockIsStreamMode; - private static bool mockIsStreamMode; - private Dictionary mockGlobalStatesDictionary = new(); - private Dictionary mockPlayerStatesDictionary = new(); + public Action OnPlayerJoin(Action onPlayerJoinCallback) + { + Debug.Log("On Player Join"); + var testPlayer = PlayroomKit.GetPlayerById(PlayerId); + PlayroomKit.IPlayroomBase.OnPlayerJoinCallbacks.Add(onPlayerJoinCallback); + PlayroomKit.IPlayroomBase.__OnPlayerJoinCallbackHandler(PlayerId); - public Action OnPlayerJoin(Action onPlayerJoinCallback) + void Unsubscribe() { - Debug.Log("On Player Join"); - var testPlayer = GetPlayer(PlayerId); - IPlayroomBase.OnPlayerJoinCallbacks.Add(onPlayerJoinCallback); - IPlayroomBase.__OnPlayerJoinCallbackHandler(PlayerId); - - void Unsubscribe() - { - IPlayroomBase.OnPlayerJoinCallbacks.Remove(onPlayerJoinCallback); - } - - return Unsubscribe; + PlayroomKit.IPlayroomBase.OnPlayerJoinCallbacks.Remove(onPlayerJoinCallback); } - public void InsertCoin(InitOptions options = null, Action onLaunchCallBack = null, - Action onDisconnectCallback = null) - { - isPlayRoomInitialized = true; - Debug.Log("Coin Inserted"); - string optionsJson = null; - if (options != null) optionsJson = SerializeInitOptions(options); - onLaunchCallBack?.Invoke(); - } + return Unsubscribe; + } - public Player MyPlayer() - { - return GetPlayer(PlayerId); - } + public void InsertCoin(InitOptions options = null, Action onLaunchCallBack = null, + Action onDisconnectCallback = null) + { + PlayroomKit.IsPlayRoomInitialized = true; + Debug.Log("Coin Inserted"); + string optionsJson = null; + if (options != null) optionsJson = Helpers.SerializeInitOptions(options); + onLaunchCallBack?.Invoke(); + } - public Player Me() - { - return GetPlayer(PlayerId); - } + public PlayroomKit.Player MyPlayer() + { + return PlayroomKit.GetPlayerById(PlayerId); + } - public bool IsHost() - { - return true; - } + public PlayroomKit.Player Me() + { + return PlayroomKit.GetPlayerById(PlayerId); + } - public string GetRoomCode() - { - return "mock123"; - } + public bool IsHost() + { + return true; + } - public void StartMatchmaking(Action callback = null) - { - Debug.Log("Matchmaking doesn't work in local mock mode!"); - callback?.Invoke(); - } + public string GetRoomCode() + { + return "mock123"; + } - public void SetState(string key, T value, bool reliable = false) - { - if (mockGlobalStates.ContainsKey(key)) - mockGlobalStates[key] = value; - else - mockGlobalStates.Add(key, value); + public void StartMatchmaking(Action callback = null) + { + Debug.Log("Matchmaking doesn't work in local mock mode!"); + callback?.Invoke(); + } - CallbackManager.InvokeCallback(key, value as string); - } + public void SetState(string key, T value, bool reliable = false) + { + if (mockGlobalStates.ContainsKey(key)) + mockGlobalStates[key] = value; + else + mockGlobalStates.Add(key, value); + CallbackManager.InvokeCallback(key, value as string); + } - public T GetState(string key) + public T GetState(string key) + { + if (mockGlobalStates.TryGetValue(key, out var value) && value is T typedValue) { - if (mockGlobalStates.TryGetValue(key, out var value) && value is T typedValue) + try { - try - { - // Attempt to convert the string to the expected type T - return (T)Convert.ChangeType(typedValue, typeof(T)); - } - catch (InvalidCastException) - { - Debug.LogWarning($"Failed to convert the value of key '{key}' to type {typeof(T)}."); - return default; - } + // Attempt to convert the string to the expected type T + return (T)Convert.ChangeType(typedValue, typeof(T)); } - else + catch (InvalidCastException) { - Debug.LogWarning($"No {key} in States"); + Debug.LogWarning($"Failed to convert the value of key '{key}' to type {typeof(T)}."); return default; } } - - public void OnDisconnect(Action callback) + else { - callback?.Invoke(); - } - - public bool IsStreamScreen() - { - return mockIsStreamMode; - } - - public void WaitForState(string stateKey, Action onStateSetCallback = null) - { - if (onStateSetCallback == null) - return; - - CallbackManager.RegisterCallback(onStateSetCallback, stateKey); + Debug.LogWarning($"No {key} in States"); + return default; } + } - public void WaitForPlayerState(string playerID, string stateKey, Action onStateSetCallback = null) - { - CallbackManager.RegisterCallback(onStateSetCallback, $"{stateKey}_{playerID}"); - } + public void OnDisconnect(Action callback) + { + callback?.Invoke(); + } - public void ResetStates(string[] keysToExclude = null, Action OnStatesReset = null) - { - List keysToRemove = - mockGlobalStatesDictionary.Keys.Where(key => !keysToExclude.Contains(key)).ToList(); - foreach (string key in keysToRemove) mockGlobalStatesDictionary.Remove(key); - OnStatesReset?.Invoke(); - } + public bool IsStreamScreen() + { + return mockIsStreamMode; + } - public void ResetPlayersStates(string[] keysToExclude = null, Action OnStatesReset = null) - { - if (keysToExclude == null || keysToExclude.Length == 0) - { - keysToExclude = Array.Empty(); - } + public void WaitForState(string stateKey, Action onStateSetCallback = null) + { + if (onStateSetCallback == null) + return; - List keysToRemove = - mockPlayerStatesDictionary.Keys.Where(key => !keysToExclude.Contains(key)).ToList(); + CallbackManager.RegisterCallback(onStateSetCallback, stateKey); + } - foreach (string key in keysToRemove) - { - mockPlayerStatesDictionary.Remove(key); - } + public void WaitForPlayerState(string playerID, string stateKey, Action onStateSetCallback = null) + { + CallbackManager.RegisterCallback(onStateSetCallback, $"{stateKey}_{playerID}"); + } - OnStatesReset?.Invoke(); - } + public void ResetStates(string[] keysToExclude = null, Action onStatesReset = null) + { + List keysToRemove = + mockGlobalStates.Keys.Where(key => !keysToExclude.Contains(key)).ToList(); + foreach (string key in keysToRemove) mockGlobalStates.Remove(key); + onStatesReset?.Invoke(); + } - public void CreateJoyStick(JoystickOptions options) + public void ResetPlayersStates(string[] keysToExclude = null, Action onStatesReset = null) + { + if (keysToExclude == null || keysToExclude.Length == 0) { - throw new NotImplementedException(); + keysToExclude = Array.Empty(); } - public Dpad DpadJoystick() - { - throw new NotImplementedException(); - } + List keysToRemove = + PlayroomKit.Player.LocalPlayerService.GetMockPlayerStates().Keys.Where(key => !keysToExclude.Contains(key)) + .ToList(); - public void UnsubscribeOnQuit() + foreach (string key in keysToRemove) { - throw new NotImplementedException(); + PlayroomKit.Player.LocalPlayerService.GetMockPlayerStates().Remove(key); } + + onStatesReset?.Invoke(); + } + + public void CreateJoyStick(JoystickOptions options) + { + throw new NotImplementedException(); + } + + public Dpad DpadJoystick() + { + throw new NotImplementedException(); + } + + public void UnsubscribeOnQuit() + { + throw new NotImplementedException(); } } } \ No newline at end of file diff --git a/Assets/PlayroomKit/modules/MockMode/MockCallbackInvoker.cs b/Assets/PlayroomKit/modules/MockMode/MockCallbackInvoker.cs index c416a8f..4ef1aac 100644 --- a/Assets/PlayroomKit/modules/MockMode/MockCallbackInvoker.cs +++ b/Assets/PlayroomKit/modules/MockMode/MockCallbackInvoker.cs @@ -30,13 +30,12 @@ public void SetCallback(Action cb, string key) public void ExecuteCallback(string result) - { + { StartCoroutine(ExecuteCallbackCoroutine(result)); } public void ExecuteCallback(string[] result) { - StartCoroutine(ExecuteCallbackCoroutine(result)); } @@ -48,7 +47,7 @@ public void ExecuteCallback() private IEnumerator ExecuteCallbackCoroutine(string result) { yield return new WaitForEndOfFrame(); - + CallbackManager.InvokeCallback(gameObject.name, result); Destroy(gameObject); } diff --git a/Assets/PlayroomKit/modules/MockMode/MockModeHandler.cs b/Assets/PlayroomKit/modules/MockMode/MockModeHandler.cs deleted file mode 100644 index 9f76267..0000000 --- a/Assets/PlayroomKit/modules/MockMode/MockModeHandler.cs +++ /dev/null @@ -1,187 +0,0 @@ -using System; - -namespace Playroom -{ - /// - /// Handles which mode is being used - /// - public partial class PlayroomKit - { - public enum MockModeSelector - { - Local, - } - - public static MockModeSelector CurrentMockMode { get; set; } = MockModeSelector.Local; - - // TODO : This will be removed when BrowserMockMode service is updated using the new architecture. - /* - private static void ExecuteMockModeAction(Action localAction, Action browserAction) - { - switch (CurrentMockMode) - { - case MockModeSelector.Local: - localAction(); - break; -#if UNITY_EDITOR - case MockModeSelector.BrowserBridge: - browserAction(); - break; -#endif - default: - throw new ArgumentOutOfRangeException(); - } - } - - private static T ExecuteMockModeFunc(Func localFunc, Func browserFunc) - { - return CurrentMockMode switch - { - MockModeSelector.Local => localFunc(), -#if UNITY_EDITOR - MockModeSelector.BrowserBridge => browserFunc(), -#endif - _ => throw new ArgumentOutOfRangeException(), - }; - } - - private static void MockInsertCoin(InitOptions options, Action onLaunchCallBack) - { - ExecuteMockModeAction( - () => MockInsertCoinLocal(options, onLaunchCallBack), - () => MockInsertCoinBrowser(options, onLaunchCallBack)); - } - - private static void MockOnPlayerJoin(Action onPlayerJoinCallback) - { - ExecuteMockModeAction( - () => MockOnPlayerJoinLocal(onPlayerJoinCallback), - () => MockOnPlayerJoinBrowser(onPlayerJoinCallback)); - } - - private static void MockSetState(string key, object value, bool reliable = false) - { - ExecuteMockModeAction( - () => MockSetStateLocal(key, value), - () => MockSetStateBrowser(key, value, reliable)); - } - - private static void MockSetState(string playerID, string key, object value, bool reliable = false) - { - ExecuteMockModeAction( - () => MockPlayerSetStateLocal(key, value), - () => MockPlayerSetStateBrowser(playerID, key, value, reliable)); - } - - private static T MockGetState(string key) - { - return ExecuteMockModeFunc( - () => MockGetStateLocal(key), - () => MockGetStateBrowser(key)); - } - - private static T MockGetState(string playerID, string key) - { - return ExecuteMockModeFunc( - () => MockPlayerGetStateLocal(key), - () => MockPlayerGetStateBrowser(playerID, key)); - } - - private static string MockGetRoomCode() - { - return ExecuteMockModeFunc( - MockGetRoomCodeLocal, - MockGetRoomCodeBrowser); - } - - private static Player MockMyPlayer() - { - return ExecuteMockModeFunc( - MockMyPlayerLocal, - MockMyPlayerBrowser); - } - - private static Player MockMe() => MockMyPlayer(); - - private static bool MockIsHost() - { - return ExecuteMockModeFunc( - MockIsHostLocal, - MockIsHostBrowser); - } - - private static bool MockIsStreamScreen() - { - return ExecuteMockModeFunc( - MockIsStreamScreenLocal, - MockIsStreamScreenBrowser); - } - - private static Player.Profile MockGetProfile(string id = null) - { - return ExecuteMockModeFunc( - MockGetProfileLocal, - () => MockGetProfileBrowser(id) - ); - } - - private static void MockStartMatchmaking() - { - ExecuteMockModeAction( - MockStartMatchmakingLocal, - MockStartMatchmakingBrowser); - } - - private static void MockKick(string id = null, Action onKickCallback = null) - { - ExecuteMockModeAction( - () => MockKickLocal(onKickCallback), - () => MockKickBrowser(id)); - } - - private static void MockResetStates(string[] keysToExclude = null, Action onKickCallback = null) - { - ExecuteMockModeAction( - () => MockResetStatesLocal(keysToExclude, onKickCallback), - () => MockResetStatesBrowser(keysToExclude, onKickCallback)); - } - - private static void MockResetPlayersStates(string[] keysToExclude = null, Action onKickCallback = null, - string serializedKeysToExclude = null) - { - ExecuteMockModeAction( - () => MockResetPlayersStatesLocal(keysToExclude, onKickCallback), - () => ResetPlayersStatesBrowser(serializedKeysToExclude, onKickCallback)); - } - - private static void MockOnDisconnect(Action callback) - { - ExecuteMockModeAction( - () => MockOnDisconnectLocal(callback), - () => MockOnDisconnectBrowser(callback)); - } - - private static void MockWaitForState(string state, Action callback) - { - ExecuteMockModeAction( - () => MockWaitForStateLocal(state, callback), - () => MockWaitForStateBrowser(state, callback)); - } - - private static void MockRpcRegister(string name, Action callback, string responseReturn) - { - ExecuteMockModeAction( - () => MockRpcRegisterLocal(name, callback), - () => MockRpcRegisterBrowser(name, callback)); - } - - private static void MockRpcCall(string name, object data, RpcMode mode, Action callbackOnResponse = null) - { - ExecuteMockModeAction( - () => MockRpcCallLocal(name, data, mode, callbackOnResponse), - () => MockRpcCallBrowser(name, data, mode, callbackOnResponse)); - } - - */ - } -} \ No newline at end of file diff --git a/Assets/PlayroomKit/modules/MockMode/MockModeHandler.cs.meta b/Assets/PlayroomKit/modules/MockMode/MockModeHandler.cs.meta deleted file mode 100644 index 944311a..0000000 --- a/Assets/PlayroomKit/modules/MockMode/MockModeHandler.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: e27e12b3f407ec04dac024a877925d98 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/PlayroomKit/modules/Options/ButtonOptions.cs b/Assets/PlayroomKit/modules/Options/ButtonOptions.cs new file mode 100644 index 0000000..79ac9c4 --- /dev/null +++ b/Assets/PlayroomKit/modules/Options/ButtonOptions.cs @@ -0,0 +1,12 @@ +using System; + +namespace Playroom +{ + [Serializable] + public class ButtonOptions + { + public string id = null; + public string label = ""; + public string icon = null; + } +} \ No newline at end of file diff --git a/Assets/PlayroomKit/modules/Options/ButtonOptions.cs.meta b/Assets/PlayroomKit/modules/Options/ButtonOptions.cs.meta new file mode 100644 index 0000000..056ffac --- /dev/null +++ b/Assets/PlayroomKit/modules/Options/ButtonOptions.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: e9fe99b4ca9540b2ab4d5021d4166096 +timeCreated: 1731319870 \ No newline at end of file diff --git a/Assets/PlayroomKit/modules/Options/Dpad.cs b/Assets/PlayroomKit/modules/Options/Dpad.cs new file mode 100644 index 0000000..bf44ed7 --- /dev/null +++ b/Assets/PlayroomKit/modules/Options/Dpad.cs @@ -0,0 +1,11 @@ +using System; + +namespace Playroom +{ + [Serializable] + public class Dpad + { + public string x; + public string y; + } +} \ No newline at end of file diff --git a/Assets/PlayroomKit/modules/Options/Dpad.cs.meta b/Assets/PlayroomKit/modules/Options/Dpad.cs.meta new file mode 100644 index 0000000..ff56ecb --- /dev/null +++ b/Assets/PlayroomKit/modules/Options/Dpad.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 2df12f4b58124b098ef47e9a3f1e46be +timeCreated: 1731320197 \ No newline at end of file diff --git a/Assets/PlayroomKit/modules/Options/InitOptions.cs b/Assets/PlayroomKit/modules/Options/InitOptions.cs index f99cfcc..8cd8ace 100644 --- a/Assets/PlayroomKit/modules/Options/InitOptions.cs +++ b/Assets/PlayroomKit/modules/Options/InitOptions.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using JetBrains.Annotations; namespace Playroom { @@ -14,7 +15,8 @@ public class InitOptions public bool skipLobby = false; public int reconnectGracePeriod = 0; public int? maxPlayersPerRoom; - public string? gameId; + [CanBeNull] + public string gameId; public bool discord = false; public Dictionary defaultStates = null; diff --git a/Assets/PlayroomKit/modules/Options/JoystickOptions.cs b/Assets/PlayroomKit/modules/Options/JoystickOptions.cs new file mode 100644 index 0000000..4aafa69 --- /dev/null +++ b/Assets/PlayroomKit/modules/Options/JoystickOptions.cs @@ -0,0 +1,9 @@ +namespace Playroom +{ + public class JoystickOptions + { + public string type = "angular"; + public ButtonOptions[] buttons; + public ZoneOptions zones = null; + } +} \ No newline at end of file diff --git a/Assets/PlayroomKit/modules/Options/JoystickOptions.cs.meta b/Assets/PlayroomKit/modules/Options/JoystickOptions.cs.meta new file mode 100644 index 0000000..bd9450f --- /dev/null +++ b/Assets/PlayroomKit/modules/Options/JoystickOptions.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 21cea17778af46bba2b1a491b64e3d63 +timeCreated: 1731319704 \ No newline at end of file diff --git a/Assets/PlayroomKit/modules/Options/ZoneOptions.cs b/Assets/PlayroomKit/modules/Options/ZoneOptions.cs new file mode 100644 index 0000000..037c42d --- /dev/null +++ b/Assets/PlayroomKit/modules/Options/ZoneOptions.cs @@ -0,0 +1,10 @@ +namespace Playroom +{ + public class ZoneOptions + { + public ButtonOptions up = null; + public ButtonOptions down = null; + public ButtonOptions left = null; + public ButtonOptions right = null; + } +} \ No newline at end of file diff --git a/Assets/PlayroomKit/modules/Options/ZoneOptions.cs.meta b/Assets/PlayroomKit/modules/Options/ZoneOptions.cs.meta new file mode 100644 index 0000000..0519359 --- /dev/null +++ b/Assets/PlayroomKit/modules/Options/ZoneOptions.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: efd646e5b93a4cf6af7760bb0de4fa28 +timeCreated: 1731319754 \ No newline at end of file diff --git a/Assets/PlayroomKit/modules/Player/LocalPlayerService.cs b/Assets/PlayroomKit/modules/Player/LocalPlayerService.cs index 26d2543..d55d81b 100644 --- a/Assets/PlayroomKit/modules/Player/LocalPlayerService.cs +++ b/Assets/PlayroomKit/modules/Player/LocalPlayerService.cs @@ -18,9 +18,13 @@ public LocalPlayerService(string id) } private Dictionary<(string playerID, string stateKey), Action> stateCallbacks = new(); + private static Dictionary mockPlayerStatesDictionary = new(); - private static Dictionary mockPlayerStatesDictionary = new(); + public static Dictionary GetMockPlayerStates() + { + return mockPlayerStatesDictionary; + } public void SetStateHelper(string key, T value, bool reliable = false) { @@ -100,7 +104,7 @@ public Action OnQuit(Action callback) public void Kick(Action onKickCallBack = null) { - var player = GetPlayer(_id); + var player = GetPlayerById(_id); Players.Remove(player.id); IPlayerBase.onKickCallBack?.Invoke(); } diff --git a/Assets/PlayroomKit/modules/Player/Player.cs b/Assets/PlayroomKit/modules/Player/Player.cs index bf85029..ce43740 100644 --- a/Assets/PlayroomKit/modules/Player/Player.cs +++ b/Assets/PlayroomKit/modules/Player/Player.cs @@ -15,92 +15,98 @@ public partial class PlayroomKit { public partial class Player { - //DI public string id; IPlayerBase _playerService; private static int totalObjects = 0; + public Player(string playerID, IPlayerBase playerService) { this.id = playerID; this._playerService = playerService; totalObjects++; } - + public void SetState(string key, int value, bool reliable = false) { - if (!isPlayRoomInitialized) + if (!IsPlayRoomInitialized) { Debug.LogError("PlayroomKit is not loaded! Please make sure to call InsertCoin first."); return; } + _playerService.SetState(key, value, reliable); } public void SetState(string key, float value, bool reliable = false) { - if (!isPlayRoomInitialized) + if (!IsPlayRoomInitialized) { Debug.LogError("PlayroomKit is not loaded! Please make sure to call InsertCoin first."); return; } + _playerService.SetState(key, value, reliable); } - + public void SetState(string key, bool value, bool reliable = false) { - if (!isPlayRoomInitialized) + if (!IsPlayRoomInitialized) { Debug.LogError("PlayroomKit is not loaded! Please make sure to call InsertCoin first."); return; } + _playerService.SetState(key, value, reliable); } public void SetState(string key, string value, bool reliable = false) { - if (!isPlayRoomInitialized) + if (!IsPlayRoomInitialized) { Debug.LogError("PlayroomKit is not loaded! Please make sure to call InsertCoin first."); return; } + _playerService.SetState(key, value, reliable); } // Overload for complex objects, which will be serialized to JSON public void SetState(string key, object value, bool reliable = false) { - if (!isPlayRoomInitialized) + if (!IsPlayRoomInitialized) { Debug.LogError("PlayroomKit is not loaded! Please make sure to call InsertCoin first."); return; } + _playerService.SetState(key, value, reliable); } - + public T GetState(string key) { Type type = typeof(T); var value = _playerService.GetState(key); return value; } - + public Profile GetProfile() { - if (!isPlayRoomInitialized) + if (!IsPlayRoomInitialized) { Debug.LogError("[Mock Mode] Playroom not initialized yet! Please call InsertCoin."); return default; } + return _playerService.GetProfile(); } - + public Action OnQuit(Action callback) { - if (!isPlayRoomInitialized) + if (!IsPlayRoomInitialized) { Debug.LogError("PlayroomKit is not loaded!. Please make sure to call InsertCoin first."); return null; @@ -108,38 +114,39 @@ public Action OnQuit(Action callback) return _playerService.OnQuit(callback); } - + public void Kick(Action OnKickCallBack = null) { - if (!isPlayRoomInitialized) - { + if (!IsPlayRoomInitialized) + { Debug.LogError("[Mock Mode] Playroom not initialized yet! Please call InsertCoin."); return; } - + _playerService.Kick(OnKickCallBack); } - + public void WaitForState(string StateKey, Action onStateSetCallback = null) { - if (!isPlayRoomInitialized) + if (!IsPlayRoomInitialized) { Debug.LogError("Playroom not initialized yet! Please call InsertCoin."); } _playerService.WaitForState(StateKey, onStateSetCallback); } - + //DI END - - - + + [Serializable] public class Profile { - [NonSerialized] public UnityEngine.Color color; + [NonSerialized] + public UnityEngine.Color color; - [FormerlySerializedAs("jsonColor")] public PlayerProfileColor playerProfileColor; + [FormerlySerializedAs("jsonColor")] + public PlayerProfileColor playerProfileColor; public string name; public string photo; @@ -153,19 +160,17 @@ public class PlayerProfileColor public int hex; } } - - + private void OnQuitDefaultCallback() { - if (!isPlayRoomInitialized) + if (!IsPlayRoomInitialized) { Debug.LogError("Playroom not initialized yet! Please call InsertCoin."); } Players.Remove(id); } - } } } \ No newline at end of file diff --git a/Assets/PlayroomKit/modules/Player/PlayerService.cs b/Assets/PlayroomKit/modules/Player/PlayerService.cs index 79955eb..975f0ff 100644 --- a/Assets/PlayroomKit/modules/Player/PlayerService.cs +++ b/Assets/PlayroomKit/modules/Player/PlayerService.cs @@ -120,7 +120,7 @@ public T GetState(string key) public Profile GetProfile() { var jsonString = _interop.GetProfileWrapper(_id); - var profileData = ParseProfile(jsonString); + var profileData = Helpers.ParseProfile(jsonString); return profileData; } diff --git a/Assets/PlayroomKit/modules/PlayroomService.cs b/Assets/PlayroomKit/modules/PlayroomService.cs index 73e9af0..fbee435 100644 --- a/Assets/PlayroomKit/modules/PlayroomService.cs +++ b/Assets/PlayroomKit/modules/PlayroomService.cs @@ -10,16 +10,16 @@ namespace Playroom { public partial class PlayroomKit { - public class PlayroomService : IPlayroomBase, IPlayroomBuildExtensions + public class PlayroomBuildService : IPlayroomBase, IPlayroomBuildExtensions { private readonly IInterop _interop; - public PlayroomService() + public PlayroomBuildService() { _interop = new PlayroomKitInterop(); } - public PlayroomService(IInterop interop) + public PlayroomBuildService(IInterop interop) { _interop = interop; } @@ -47,14 +47,14 @@ void Unsubscribe() public void InsertCoin(InitOptions options = null, Action onLaunchCallBack = null, Action onDisconnectCallback = null) { - isPlayRoomInitialized = true; + IsPlayRoomInitialized = true; var onLaunchCallBackKey = CallbackManager.RegisterCallback(onLaunchCallBack, "onLaunchCallBack"); var onDisconnectCallBackKey = CallbackManager.RegisterCallback(onDisconnectCallback, "onDisconnectCallBack"); string optionsJson = null; - if (options != null) optionsJson = SerializeInitOptions(options); + if (options != null) optionsJson = Helpers.SerializeInitOptions(options); if (options.skipLobby == false) { @@ -71,7 +71,7 @@ public void InsertCoin(InitOptions options = null, Action onLaunchCallBack = nul public Player MyPlayer() { var id = _interop.MyPlayerWrapper(); - return GetPlayer(id); + return GetPlayerById(id); } public Player Me() @@ -90,18 +90,15 @@ public string GetRoomCode() return _interop.GetRoomCodeWrapper(); } - static Action startMatchmakingCallback = null; public void StartMatchmaking(Action callback = null) { - startMatchmakingCallback = callback; + CallbackManager.RegisterCallback(callback, "matchMakingStarted"); _interop.StartMatchmakingWrapper(InvokeStartMatchmakingCallback); } public void SetState(string key, T value, bool reliable = false) { - //#Debug.Log("SetState "+ key + ", value is " + value + "of type " + value.GetType()); - // Use type checking to call the correct overload of SetStateWrapper if (value is string) { _interop.SetStateStringWrapper(key, (string)(object)value, reliable); @@ -118,11 +115,11 @@ public void SetState(string key, T value, bool reliable = false) { float floatValue = (float)(object)value; var floatAsString = floatValue.ToString(CultureInfo.InvariantCulture); - _interop.SetStateFloatWrapper(key, floatAsString, reliable); // Assumes float is serialized as string + _interop.SetStateFloatWrapper(key, floatAsString, reliable); } - else if (value is object) // For JSON-like object, you'd serialize it to JSON (example using Newtonsoft.Json) + else if (value is object) { - Debug.Log("SetState "+ key + ", value is " + value + "of type " + value.GetType()); + Debug.Log("SetState " + key + ", value is " + value + "of type " + value.GetType()); string jsonString = JsonUtility.ToJson(value); _interop.SetStateStringWrapper(key, jsonString, reliable); } @@ -131,26 +128,21 @@ public void SetState(string key, T value, bool reliable = false) throw new InvalidOperationException($"Unsupported type: {typeof(T).Name}"); } } - + public void SetState(string key, Dictionary values, bool reliable = false) { var jsonObject = new JSONObject(); - // Add key-value pairs to the JSON object foreach (var kvp in values) { - // Convert the value to double before adding to JSONNode var value = Convert.ToDouble(kvp.Value); jsonObject.Add(kvp.Key, value); } - // Serialize the JSON object to a string var jsonString = jsonObject.ToString(); - - // Output the JSON string _interop.SetStateDictionaryWrapper(key, jsonString, reliable); } - + public void SetState(string key, string value, bool reliable = false) { _interop.SetStateStringWrapper(key, value, reliable); @@ -202,7 +194,7 @@ public T GetState(string key) [MonoPInvokeCallback(typeof(Action))] private static void InvokeStartMatchmakingCallback() { - startMatchmakingCallback?.Invoke(); + CallbackManager.InvokeCallback("matchMakingStarted"); } [MonoPInvokeCallback(typeof(Action))] @@ -228,7 +220,7 @@ private static void __OnQuitInternalHandler(string playerId) Debug.LogError("[__OnQuitInternalHandler] Couldn't find player with id " + playerId); } } - + public void OnDisconnect(Action callback) { CallbackManager.RegisterCallback(callback); @@ -245,47 +237,48 @@ public void WaitForState(string stateKey, Action onStateSetCallback = nu CallbackManager.RegisterCallback(onStateSetCallback, stateKey); _interop.WaitForStateWrapper(stateKey, IPlayroomBase.InvokeCallback); } - - + + Action WaitForPlayerCallback = null; + public void WaitForPlayerState(string playerID, string stateKey, Action onStateSetCallback = null) { WaitForPlayerCallback = onStateSetCallback; _interop.WaitForPlayerStateWrapper(playerID, stateKey, OnStateSetCallback); } - + [MonoPInvokeCallback(typeof(Action))] void OnStateSetCallback(string data) { WaitForPlayerCallback?.Invoke(data); } - + private static Action onstatesReset; private static Action onplayersStatesReset; - public void ResetStates(string[] keysToExclude = null, Action OnStatesReset = null) + public void ResetStates(string[] keysToExclude = null, Action onStatesReset = null) { - onstatesReset = OnStatesReset; - string keysJson = keysToExclude != null ? CreateJsonArray(keysToExclude).ToString() : null; + onstatesReset = onStatesReset; + string keysJson = keysToExclude != null ? Helpers.CreateJsonArray(keysToExclude).ToString() : null; _interop.ResetStatesWrapper(keysJson, InvokeResetCallBack); } - + [MonoPInvokeCallback(typeof(Action))] private static void InvokeResetCallBack() { onstatesReset?.Invoke(); } - public void ResetPlayersStates(string[] keysToExclude = null, Action OnStatesReset = null) + public void ResetPlayersStates(string[] keysToExclude = null, Action onStatesReset = null) { - onstatesReset = OnStatesReset; - string keysJson = keysToExclude != null ? CreateJsonArray(keysToExclude).ToString() : null; + onstatesReset = onStatesReset; + string keysJson = keysToExclude != null ? Helpers.CreateJsonArray(keysToExclude).ToString() : null; _interop.ResetPlayersStatesWrapper(keysJson, InvokePlayersResetCallBack); } public void CreateJoyStick(JoystickOptions options) { - var jsonStr = ConvertJoystickOptionsToJson(options); + string jsonStr = Helpers.ConvertJoystickOptionsToJson(options); _interop.CreateJoystickWrapper(jsonStr); } @@ -306,7 +299,7 @@ private static void InvokePlayersResetCallBack() { onplayersStatesReset?.Invoke(); } - + [MonoPInvokeCallback(typeof(Action))] private static void onDisconnectCallbackHandler(string key) @@ -328,7 +321,7 @@ private void UnsubscribeOnPlayerJoin(string callbackID) { _interop.UnsubscribeOnPlayerJoinWrapper(callbackID); } - + // GETTERS private string GetStateString(string key) { diff --git a/Assets/PlayroomKit/modules/PlayroomkitDevManager.cs b/Assets/PlayroomKit/modules/PlayroomkitDevManager.cs index aaac243..d6065f7 100644 --- a/Assets/PlayroomKit/modules/PlayroomkitDevManager.cs +++ b/Assets/PlayroomKit/modules/PlayroomkitDevManager.cs @@ -1,33 +1,30 @@ using System; using System.Collections.Generic; -using UBB; using UnityEngine; #if UNITY_EDITOR using ParrelSync; +using UBB; #endif namespace Playroom { public class PlayroomkitDevManager : MonoBehaviour { - [SerializeField] private PlayroomKit.MockModeSelector mockMode = PlayroomKit.CurrentMockMode; + [SerializeField] + private PlayroomKit.MockModeSelector mockMode = PlayroomKit.CurrentMockMode; - [Tooltip("InsertCoin() must be called in order to connect PlayroomKit server.\n\nChoose the gameObject (with the script) which calls InsertCoin.\n\nRead More in the docs")] + [Tooltip( + "InsertCoin() must be called in order to connect PlayroomKit server.\n\nChoose the gameObject (with the script) which calls InsertCoin.\n\nRead More in the docs")] [SerializeField] private GameObject insertCoinCaller; - // [SerializeField] private bool toggleDebugLogs = false; - private static PlayroomkitDevManager Instance { get; set; } #if UNITY_EDITOR private void Awake() { -#if UNITY_EDITOR - if (ClonesManager.IsClone()) UnityBrowserBridge.Instance.httpServerPort += 1; -#endif if (Instance == null) { Instance = this; @@ -38,10 +35,9 @@ private void Awake() Destroy(gameObject); } - // if (PlayroomKit.CurrentMockMode == PlayroomKit.MockModeSelector.BrowserBridge) - // UnityBrowserBridge.Instance.StartUBB(); - UpdateMockMode(); + UnityBrowserBridge.Instance.RegisterGameObject("InsertCoin", insertCoinCaller); + UnityBrowserBridge.Instance.RegisterGameObject("devManager", gameObject); } private void OnValidate() @@ -52,22 +48,17 @@ private void OnValidate() private void UpdateMockMode() { PlayroomKit.CurrentMockMode = mockMode; - PlayroomKit.RegisterGameObject("InsertCoin", insertCoinCaller); - PlayroomKit.RegisterGameObject("devManager", gameObject); + } - // Called from JS side for onPlayerJoin + /// + /// This is invoked from the JS bridge, when OnPlayerJoin is called, this is used to pass the id from playroom to unity. + /// + /// private void GetPlayerID(string playerId) { - PlayroomKit.MockOnPlayerJoinWrapper(playerId); + BrowserMockService.MockOnPlayerJoinWrapper(playerId); } - - private string InvokeWaitForState(string stateValue) - { - Debug.Log(stateValue); - return stateValue; - } - #endif } } \ No newline at end of file diff --git a/Assets/PlayroomKit/modules/RPC/RPC.cs b/Assets/PlayroomKit/modules/RPC/RPC.cs index 97f694e..080dd37 100644 --- a/Assets/PlayroomKit/modules/RPC/RPC.cs +++ b/Assets/PlayroomKit/modules/RPC/RPC.cs @@ -1,8 +1,5 @@ using System; -using System.Collections; using System.Collections.Generic; -using System.Runtime.InteropServices; -using AOT; using SimpleJSON; using UnityEngine; @@ -27,7 +24,6 @@ public RPC(PlayroomKit playroomKit, IInterop interop) _interop = interop; } - public void RpcRegister(string name, Action rpcRegisterCallback, string onResponseReturn = null) { @@ -36,7 +32,6 @@ public void RpcRegister(string name, Action rpcRegisterCallback, _interop.RpcRegisterWrapper(name, IRPC.InvokeRpcRegisterCallBack, onResponseReturn); } - public void RpcCall(string name, object data, RpcMode mode, Action callbackOnResponse = null) { @@ -77,8 +72,6 @@ public void RpcCall(string name, object data, Action callbackOnResponse = null) { RpcCall(name, data, RpcMode.ALL, callbackOnResponse); } - } - } } \ No newline at end of file diff --git a/Assets/PlayroomKit/modules/RPC/RPCLocal.cs b/Assets/PlayroomKit/modules/RPC/RPCLocal.cs index ba2f13d..2a93c99 100644 --- a/Assets/PlayroomKit/modules/RPC/RPCLocal.cs +++ b/Assets/PlayroomKit/modules/RPC/RPCLocal.cs @@ -25,7 +25,7 @@ public void RpcCall(string name, object data, RpcMode mode, Action callbackOnRes mockResponseCallbacks.TryAdd(name, callbackOnResponse); string stringData = Convert.ToString(data); - var player = GetPlayer("mockplayerID123"); + var player = GetPlayerById("mockplayerID123"); if (mockRegisterCallbacks.TryGetValue(name, out var responseHandler)) { diff --git a/Assets/Scripts/GameManager.cs b/Assets/Scripts/GameManager.cs index afa4401..b12f361 100644 --- a/Assets/Scripts/GameManager.cs +++ b/Assets/Scripts/GameManager.cs @@ -37,7 +37,7 @@ void Start() }, () => { _playroomKit.OnPlayerJoin(AddPlayer); - _playroomKit.RpcRegister("score", (data, caller) => print($"{data} by {PlayroomKit.GetPlayer(caller).GetProfile().name}")); + _playroomKit.RpcRegister("score", (data, caller) => print($"{data} by {_playroomKit.GetPlayer(caller).GetProfile().name}")); }, () => { Debug.Log("OnDisconnect callback"); }); } diff --git a/Assets/WebGLTemplates/DiscordTemplate/index.html b/Assets/WebGLTemplates/DiscordTemplate/index.html index 876211b..b242fb7 100644 --- a/Assets/WebGLTemplates/DiscordTemplate/index.html +++ b/Assets/WebGLTemplates/DiscordTemplate/index.html @@ -1,18 +1,19 @@ - - + + Unity WebGL Player | {{{ PRODUCT_NAME }}} - - -#if SHOW_DIAGNOSTICS - + + + #if SHOW_DIAGNOSTICS + -#endif + #endif