Exemple #1
0
        /// <summary>
        /// Performs scene transition.
        /// </summary>
        /// <param name="config">Using <see cref="ChangeScene"/> or <see cref="AddScene"/> is recommended.</param>
        /// <returns></returns>
        protected async UniTask PerformSceneTransition <T>(SceneTransitionConfiguration <T> config)
        {
            if (config.PerformTransition && TransitionBackgroundController == null)
            {
                Debug.LogWarning(
                    "Scene change / addition with a transition requested, " +
                    "but there is no transition background attached.\n" +
                    "Did you assign one in UniSwitcherInstaller?"
                    );
            }

            if (config.PerformTransition && TransitionBackgroundController != null)
            {
                while (TransitionBackgroundController.GetTransitionState() != TransitionState.Ready)
                {
                    await UniTask.Yield();
                }
            }

            if (!config.IsAdditive)
            {
                DontDestroyOnLoad(this);
            }

            if (!config.SupressProgressBar && sceneProgressBarController != null)
            {
                sceneProgressBarController.Enable();
                sceneProgressBarController.SetDDoL();
            }

            if (config.Delay <= 0.0001f)
            {
                // No delay or negligible delay
                if (config.PerformTransition && TransitionBackgroundController != null)
                {
                    TransitionBackgroundController.TriggerTransitionIn();
                    await UniTask.Delay(TimeSpan.FromSeconds(0.1));

                    while (TransitionBackgroundController.GetTransitionState() == TransitionState.In)
                    {
                        await UniTask.Yield();
                    }
                }

                _sceneLoader.LoadScene(config.DestinationScene, config.IsAdditive,
                                       config.DataToTransfer);
            }
            else
            {
                _sceneLoader.LoadSceneWithDelay(config.DestinationScene, config.Delay, config.IsAdditive,
                                                config.DataToTransfer);
                if (config.PerformTransition && TransitionBackgroundController != null)
                {
                    // In case of delayed transition, trigger transition 1 second before scene change
                    TransitionBackgroundController.TriggerTransitionIn();
                    await UniTask.Delay(TimeSpan.FromSeconds(config.Delay - 1));

                    while (TransitionBackgroundController.GetTransitionState() == TransitionState.In)
                    {
                        await UniTask.Yield();
                    }
                }
            }

            while (!_sceneLoader.IsLoaded(config.DestinationScene) ||
                   (TransitionBackgroundController != null && config.PerformTransition &&
                    !TransitionBackgroundController.IsTransitionAllowed()))
            {
                await UniTask.Yield();
            }

            TransitionBackgroundController?.DetectMainCamera();

            var entryPointTask = _bootStrapper.TriggerEntryPoint();

            while (entryPointTask.Status == UniTaskStatus.Pending)
            {
                await UniTask.Yield();
            }

            if (!config.SupressProgressBar && sceneProgressBarController != null)
            {
                sceneProgressBarController.SetProgress(1f);
                if (config.IsAdditive)
                {
                    sceneProgressBarController.Disable();
                }
                else
                {
                    sceneProgressBarController.Close().Forget(Debug.LogException);
                }
            }

            if (config.PerformTransition)
            {
                TransitionBackgroundController?.TriggerTransitionOut();
            }

            if (!config.IsAdditive)
            {
                Destroy(gameObject);
            }
        }
        async UniTask SpiralAsync(string text)
        {
            float height          = 0;
            var   angleWithCamera = Vector3.Angle(Camera.main.transform.forward, transform.forward);

            meshPro.text = text;
            meshPro.ForceMeshUpdate();
            //メッシュ情報をキャシュー
            cachedMeshInfo = textInfo.CopyMeshInfoVertexData();
            Color32 c0       = tmpText.color;
            float   interval = 33f;

            while (true)
            {
                if ((bool)(colorToken?.IsCancellationRequested))
                {
                    colorToken.Dispose();
                    colorToken = null;
                    return;
                }
                //var wideScale = ((Mathf.Abs(Camera.main.transform.localPosition.z) - 637) / 2) * 0.04f;
                //wideScale = Mathf.Min(wideScale, MinWideScale);
                //transform.localScale = new Vector3(wideScale, wideScale, wideScale);
                height += interval / 1000 * spiralUpSpeed;
                for (int i = 0; i < textInfo.characterCount; i++)
                {
                    int       materialIndex       = textInfo.characterInfo[i].materialReferenceIndex;
                    int       vertexIndex         = textInfo.characterInfo[i].vertexIndex;
                    Vector3[] sourceVertices      = cachedMeshInfo[materialIndex].vertices;
                    Vector3[] destinationVertices = textInfo.meshInfo[materialIndex].vertices;
                    if (height - i > 0)
                    {
                        destinationVertices[vertexIndex + 0] = sourceVertices[vertexIndex] + new Vector3(0, (height - i), 0);
                        destinationVertices[vertexIndex + 1] = sourceVertices[vertexIndex + 1] + new Vector3(0, (height - i), 0);
                        destinationVertices[vertexIndex + 2] = sourceVertices[vertexIndex + 2] + new Vector3(0, (height - i), 0);
                        destinationVertices[vertexIndex + 3] = sourceVertices[vertexIndex + 3] + new Vector3(0, (height - i), 0);
                    }
                    var newVertexColors = textInfo.meshInfo[materialIndex].colors32;
                    //各キャラクターの頂点の色を頂点透明度を高さの元ついてスムーズに変更
                    if (textInfo.characterInfo[i].isVisible)
                    {
                        float alpha           = 1f;
                        float characterHeight = Mathf.Max(destinationVertices[vertexIndex + 0].y, 0);
                        //高さが一番下未満と一番上を超えた場合。
                        if (characterHeight <= displayStartHeight || characterHeight > vanishEndHeight)
                        {
                            alpha = 0;
                        }
                        //displayStartHeightからdisplayEndHeight徐々に表示
                        else if (characterHeight > displayStartHeight && characterHeight < displayEndHeight)
                        {
                            alpha = (characterHeight - displayStartHeight) / (displayEndHeight - displayStartHeight);
                        }
                        //vanishStartHeightからvanishEndHeight徐々に非表示
                        else if (characterHeight > vanishStartHeight && characterHeight < vanishEndHeight)
                        {
                            alpha = (vanishEndHeight - characterHeight) / (vanishEndHeight - vanishStartHeight);
                        }
                        c0 = new Color32(newVertexColors[vertexIndex + 0].r, newVertexColors[vertexIndex + 0].g, newVertexColors[vertexIndex + 0].b, (byte)(alpha * 255));
                        newVertexColors[vertexIndex + 0] = c0;
                        newVertexColors[vertexIndex + 1] = c0;
                        newVertexColors[vertexIndex + 2] = c0;
                        newVertexColors[vertexIndex + 3] = c0;
                    }
                }
                //変形した頂点をTextMeshProに入れ
                for (int i = 0; i < textInfo.meshInfo.Length; i++)
                {
                    textInfo.meshInfo[i].mesh.vertices = textInfo.meshInfo[i].vertices;
                    tmpText.UpdateGeometry(textInfo.meshInfo[i].mesh, i);
                }
                //TextMeshProの色更新
                tmpText.UpdateVertexData(TMP_VertexDataUpdateFlags.Colors32);
                await UniTask.Delay((int)interval);
            }
        }
        async UniTask <int> ICountRepository.GetCount()
        {
            await UniTask.Delay(100); // dummy wait for something process

            return(await UniTask.FromResult(this.CountDataStore.GetCount()));
        }
        public async void GetCalenderInformation(int year, int month)
        {
            await UniTask.Delay(2000);

            processResult.OnNext(new CalenderMonthEntity());
        }
 public virtual async UniTask Opening()
 {
     ViewUtility.AddAllButtonEvent(this);
     await UniTask.Delay(0);
 }
Exemple #6
0
        public static async UniTask DelayActionAsync(float delayTime, Action action, CancellationToken token)
        {
            await UniTask.Delay(TimeSpan.FromSeconds(delayTime), cancellationToken : token);

            action?.Invoke();
        }
Exemple #7
0
    /// <summary>
    /// 移动
    /// </summary>
    /// <param name="datas"></param>
    async void MoveItems(List <CaricaturePlayerModule> oldItems, List <CaricaturePlayerModule> datas)
    {
        List <CaricaturePlayerModule> oldItemList = new List <CaricaturePlayerModule>();

        oldItemList.AddRange(oldItems);
        List <CaricaturePlayerModule> newItemList = new List <CaricaturePlayerModule>();

        newItemList.AddRange(datas);
        List <CaricaturePlayerModule> moveItems = new List <CaricaturePlayerModule>();

        List <int> hidItems         = new List <int>();
        int        initialItemIndex = 0;

        for (int i = 0; i < datas.Count; i++)
        {
            CaricaturePlayerModule initialItem = datas[i];
            if (initialItemIndex >= 1)
            {
                break;
            }
            else
            {
                if (initialItem._CaricaturePlayerSpecialModuleBasics == null)
                {
                    await initialItem.Show(GetShowRect());
                }
                else
                {
                    initialItem.Show();
                }
                //设置初始位置
                CaricaturePlayerModule oldItem = null;
                if (oldItemList != null && oldItemList.Count > 0)
                {
                    oldItem = oldItemList[oldItemList.Count - 1];
                }
                initialItem._ThisRect.localPosition = GetBornTagePoint(initialItem, oldItem);
                moveItems.Add(initialItem);
                newItemList.Remove(initialItem);
                initialItemIndex++;
                if (initialItem._CaricaturePlayerSpecialModuleBasics != null)
                {
                    Debug.Log("初始");
                }
            }
        }
        //条漫第一格是否移动完毕
        bool isOneItem = false;

        //将旧item加入移动队列
        if (oldItemList != null && oldItemList.Count > 0)
        {
            float minY = _thisRect.rect.height / 2;
            minY = -(minY) + moveItems[0]._ThisRect.rect.height / 2;

            if (_theFirstScreen)
            {
                List <CaricaturePlayerModule> newMoveItems = new List <CaricaturePlayerModule>();
                newMoveItems.AddRange(oldItemList);
                newMoveItems.AddRange(moveItems);
                oldItemList.Clear();
                moveItems.Clear();
                moveItems.AddRange(newMoveItems);
            }

            isOneItem = false;
        }
        else
        {
            isOneItem = true;
        }
        bool _isMove = true;
        //获取初始移动终点
        List <Vector3> tagePoints = new List <Vector3>();

        if (!_theFirstScreen && oldItemList != null && oldItemList.Count > 0)
        {
            tagePoints = GetMoveEndPoint(moveItems, null, oldItemList[oldItemList.Count - 1], isOneItem);
        }
        else
        {
            tagePoints = GetMoveEndPoint(moveItems, null, null, isOneItem);
        }
        while (_isMove)
        {
            hidItems.Clear();
            for (int i = 0; i < moveItems.Count; i++)
            {
                CaricaturePlayerModule moveItem = moveItems[i];

                //修改item层级
                if (i != 0)
                {
                    CaricaturePlayerModule lastMonveItem = moveItems[i - 1];
                    int siblingIndex = lastMonveItem._ThisRect.GetSiblingIndex();
                    switch (moveItem._Hierarchy)
                    {
                    case 0:
                    case 1:
                        siblingIndex = siblingIndex + 1;
                        break;

                    case -1:
                        siblingIndex = siblingIndex - 1;
                        break;
                    }
                    moveItem._ThisRect.SetSiblingIndex(siblingIndex);
                }
                Vector3 tagePoint = tagePoints[i];
                float   speed     = 5;
                //左右插入速度更改
                if (moveItem._DirectionType != ChapterTool.CaricatureModuleDirectionType.Up && Mathf.Abs(moveItem._ThisRect.localPosition.x - tagePoint.x) > 1)
                {
                    speed = 20;
                }
                else
                {
                    speed = 18;
                }
                moveItem._ThisRect.localPosition = Vector3.MoveTowards(moveItem._ThisRect.localPosition, tagePoint, speed);
                //判断是否超出屏幕
                float maxY = (_thisRect.rect.height / 2) + moveItem._ThisRect.rect.height / 2;
                if (moveItem._ThisRect.localPosition.y >= maxY)
                {
                    hidItems.Add(i);
                }
            }
            //关闭超出屏幕的item
            for (int i = 0; i < hidItems.Count; i++)
            {
                HideItem(moveItems[hidItems[i]]);
                moveItems.RemoveAt(hidItems[i]);
                tagePoints.RemoveAt(hidItems[i]);
            }

            //将旧item加入移动队列
            if (oldItemList != null && oldItemList.Count > 0)
            {
                CaricaturePlayerModule oldLastItem = oldItemList[oldItemList.Count - 1];
                CaricaturePlayerModule moveOneItem = moveItems[0];

                float   tageY     = oldLastItem._ThisRect.localPosition.y - oldLastItem._ThisRect.rect.height / 2 - moveOneItem._ThisRect.rect.height / 2 - moveOneItem._Interval;
                Vector3 tagePoint = new Vector3(moveOneItem._ThisRect.localPosition.x, tageY, moveOneItem._ThisRect.localPosition.z);
                Debug.Log("_____________________________" + tagePoint);
                Debug.Log("_____________________________" + _theFirstScreen);
                Debug.Log("_____________________________" + Vector3.Distance(tagePoint, moveOneItem._ThisRect.localPosition));

                float minY = _thisRect.rect.height / 2;
                minY = -(minY) + moveOneItem._ThisRect.rect.height / 2;
                Debug.Log("_____________________________" + (moveOneItem._ThisRect.localPosition.y < minY));
                if (/*!_theFirstScreen &&*/ /*moveOneItem._ThisRect.localPosition.y< tagePoint.y*/ Vector3.Distance(tagePoint, moveOneItem._ThisRect.localPosition) < 10 && moveOneItem._ThisRect.localPosition.y < minY)
                {
                    List <CaricaturePlayerModule> newMoveItems = new List <CaricaturePlayerModule>();
                    newMoveItems.AddRange(oldItemList);
                    newMoveItems.AddRange(moveItems);
                    oldItemList.Clear();
                    moveItems.Clear();
                    moveItems.AddRange(newMoveItems);
                    if (newItemList == null || newItemList.Count <= 0)
                    {
                        tagePoints = GetMoveEndPoint(moveItems);
                    }
                }
                else
                {
                    if (newItemList == null || newItemList.Count <= 0)
                    {
                        tagePoints = GetMoveEndPoint(moveItems, null, oldLastItem);
                    }
                }
            }
            //将下一个item加入移动队列
            if (newItemList != null && newItemList.Count > 0)
            {
                CaricaturePlayerModule newFirstItem = newItemList[0];
                if (newFirstItem._CaricaturePlayerSpecialModuleBasics == null)
                {
                    //提前生成下一个item
                    if (!newFirstItem._IsShow)
                    {
                        newFirstItem.Show(GetShowRect());
                    }
                }
                else
                {
                    newFirstItem.Show();
                }

                newFirstItem._ThisRect.localPosition = GetBornTagePoint(newFirstItem);
                CaricaturePlayerModule moveLastItem = moveItems[moveItems.Count - 1];
                float yValue = (moveLastItem._ThisRect.localPosition.y - moveLastItem._ThisRect.rect.height / 2) - newFirstItem._Interval - newFirstItem._ThisRect.rect.height / 2;
                if (newFirstItem._ThisRect.localPosition.y <= yValue)
                {
                    moveItems.Add(newFirstItem);
                    newItemList.Remove(newFirstItem);
                }
                //更新移动目标终点
                if (newItemList != null && newItemList.Count > 0)
                {
                    tagePoints = GetMoveEndPoint(moveItems, newItemList[0]);
                }
                else
                {
                    tagePoints = GetMoveEndPoint(moveItems);
                }
            }
            else
            {
                if ((newItemList == null || newItemList.Count <= 0) && Vector3.Distance(moveItems[moveItems.Count - 1]._ThisRect.localPosition, tagePoints[tagePoints.Count - 1]) <= 1)
                {
                    _isMove = false;
                }
            }
            await UniTask.Delay(TimeSpan.FromMilliseconds(10));
        }
        _currShowCaricatures.Clear();
        if (oldItemList != null && oldItemList.Count > 0)
        {
            _currShowCaricatures.AddRange(oldItemList);
        }
        _currShowCaricatures.AddRange(moveItems);
        _currShowItem = _currShowCaricatures[_currShowCaricatures.Count - 1];
        if (_currShowItem != null)
        {
            _currShowItem.MoveEnd();
            if ((_currShowItem._Dialogues == null || _currShowItem._Dialogues.Count <= 0) && isOneItem)
            {
                ClickBtn();
            }
        }
        Debug.Log("移动完毕");
    }
Exemple #8
0
    private async UniTask DestroyBlocks()
    {
        await UniTask.Delay(600);

        destroyBlock.OnNext(Unit.Default);
    }
Exemple #9
0
 public static UniTask None()
 {
     return(UniTask.Delay(0));
 }
Exemple #10
0
        public IEnumerator Setup() => UniTask.ToCoroutine(async() =>
        {
            serverGo      = new GameObject("server", typeof(NetworkSceneManager), typeof(ServerObjectManager), typeof(NetworkServer));
            clientGo      = new GameObject("client", typeof(NetworkSceneManager), typeof(ClientObjectManager), typeof(NetworkClient));
            testTransport = serverGo.AddComponent <LoopbackTransport>();

            await UniTask.Delay(1);

            server = serverGo.GetComponent <NetworkServer>();
            client = clientGo.GetComponent <NetworkClient>();

            server.Transport = testTransport;
            client.Transport = testTransport;

            serverSceneManager        = serverGo.GetComponent <NetworkSceneManager>();
            clientSceneManager        = clientGo.GetComponent <NetworkSceneManager>();
            serverSceneManager.server = server;
            clientSceneManager.client = client;
            serverSceneManager.Start();
            clientSceneManager.Start();

            serverObjectManager        = serverGo.GetComponent <ServerObjectManager>();
            serverObjectManager.server = server;
            serverObjectManager.networkSceneManager = serverSceneManager;
            serverObjectManager.Start();

            clientObjectManager        = clientGo.GetComponent <ClientObjectManager>();
            clientObjectManager.client = client;
            clientObjectManager.networkSceneManager = clientSceneManager;
            clientObjectManager.Start();

            ExtraSetup();

            // create and register a prefab
            playerPrefab             = new GameObject("serverPlayer", typeof(NetworkIdentity), typeof(T));
            NetworkIdentity identity = playerPrefab.GetComponent <NetworkIdentity>();
            identity.AssetId         = Guid.NewGuid();
            clientObjectManager.RegisterPrefab(identity);

            // wait for client and server to initialize themselves
            await UniTask.Delay(1);

            // start the server
            var started = new UniTaskCompletionSource();
            server.Started.AddListener(() => started.TrySetResult());
            server.ListenAsync().Forget();

            await started.Task;

            // now start the client
            await client.ConnectAsync("localhost");

            await AsyncUtil.WaitUntilWithTimeout(() => server.connections.Count > 0);

            // get the connections so that we can spawn players
            connectionToClient = server.connections.First();
            connectionToServer = client.Connection;

            // create a player object in the server
            serverPlayerGO  = Object.Instantiate(playerPrefab);
            serverIdentity  = serverPlayerGO.GetComponent <NetworkIdentity>();
            serverComponent = serverPlayerGO.GetComponent <T>();
            serverObjectManager.AddPlayerForConnection(connectionToClient, serverPlayerGO);

            // wait for client to spawn it
            await AsyncUtil.WaitUntilWithTimeout(() => connectionToServer.Identity != null);

            clientIdentity  = connectionToServer.Identity;
            clientPlayerGO  = clientIdentity.gameObject;
            clientComponent = clientPlayerGO.GetComponent <T>();
        });
Exemple #11
0
    private async UniTask AddBlocks()
    {
        await UniTask.Delay(1000);

        addBlock.OnNext(Unit.Default);
    }
Exemple #12
0
        private async UniTask CheckAfkPlayers()
        {
            if (Provider.isServer)
            {
                await SyncPlayers();
            }

            while (m_ServiceRunning)
            {
                await UniTask.SwitchToThreadPool();

                await UniTask.Delay(10000);

                var status   = m_Configuration.GetSection("afkchecker:enabled").Get <bool>();
                var timeout  = m_Configuration.GetSection("afkchecker:timeout").Get <int>();
                var announce = m_Configuration.GetSection("afkchecker:announceAFK").Get <bool>();
                var kick     = m_Configuration.GetSection("afkchecker:kickAFK").Get <bool>();

                if (timeout < 0 || (!kick && !announce))
                {
                    continue;
                }

                if (!status || (!kick && !announce))
                {
                    continue;
                }

                foreach (var user in m_UnturnedUserDirectory.GetOnlineUsers().ToList())
                {
                    if (!user.Session.SessionData.TryGetValue("lastMovement", out object @time) || @time is not TimeSpan span)
                    {
                        continue;
                    }

                    bool afk = (DateTime.Now.TimeOfDay - span).TotalSeconds >= timeout &&
                               await m_PermissionChecker.CheckPermissionAsync(user, "afkchecker.exempt") != PermissionGrantResult.Grant;

                    if (!afk)
                    {
                        user.Session.SessionData["isAfk"] = false;
                        continue;
                    }

                    if (!user.Session.SessionData.TryGetValue("isAfk", out var unparsedAfk) || unparsedAfk is not bool isAfk)
                    {
                        continue;
                    }

                    // todo: add announceTime and kickTime (not just timeout)

                    if (announce && !isAfk)
                    {
                        await user.Provider?.BroadcastAsync(m_StringLocalizer["afk:announcement", new { Player = user.DisplayName }, new { Time = timeout }], Color.White);
                    }

                    if (kick)
                    {
                        await user.Session?.DisconnectAsync(m_StringLocalizer["afk:kicked", new { Time = timeout }]);

                        continue;
                    }

                    user.Session.SessionData["isAfk"] = true;
                }
            }
        }
Exemple #13
0
        async UniTask WaitGamePlay(StageKind stageKind, MatchType matchType)
        {
            await UniTask.Delay(500);

            SceneChangeManager.ChangeClientMultiPlayScene(stageKind, new MultiGameInfo(client, matchType));
        }
Exemple #14
0
        async UniTask WaitStageSelect(MatchType matchType)
        {
            await UniTask.Delay(2000);

            SceneChangeManager.ChangeMultiPlayStageSelect(new MultiGameInfo(client, matchType));
        }
        private async UniTask RestoreInteractivityAfterDelay(int delayMs)
        {
            await UniTask.Delay(delayMs);

            ReactivateButton();
        }
Exemple #16
0
 public static UniTask Time(int ms, CancellationToken ct = default(CancellationToken))
 {
     return(UniTask.Delay(ms, cancellationToken: ct));
 }
Exemple #17
0
        public async UniTask <NextScreen> Run(ClientState client, WebSocket socket)
        {
            _client = client;
            _socket = socket;

            // Request that the server start a new match, and load our tile prefabs in
            // the background. Wait for both of these operations to complete before
            // attempting to instantiate any tiles.
            await UniTask.WhenAll(
                RequestStartMatch(_cancellation.Token),
                LoadTilePrefabs(_cancellation.Token));

            // TODO: Have the server data specify which player is controlled by this
            // client, rather than hard coding it to always control the east seat.
            _seat = Wind.East;

            // Register input events from the player's hand.
            var playerHand = _hands[(int)_seat];

            // Once we have the match data, instantiate the tiles for each player's
            // starting hand.
            //
            // TODO: Move tile placement logic into `PlayerHand`. The match controller
            // should only need to add and remove tiles from the hands as the match's
            // state advances, and the `PlayerHand` script should handle layout and
            // positioning.
            foreach (var seat in EnumUtils.GetValues <Wind>())
            {
                var hand = _hands[(int)seat];

                var tiles = _localState.PlayerHand(seat);

                foreach (var tile in tiles)
                {
                    hand.AddToHand(InstantiateTile(tile));
                }

                if (_localState.PlayerHasCurrentDraw(seat))
                {
                    var currentDraw = _localState.CurrentDraw(seat);
                    hand.DrawTile(InstantiateTile(currentDraw));
                }
            }

            // If the local player has the first turn, have them discard a tile now.
            if (_localState.CurrentTurn() == _seat)
            {
                await DiscardTile();
            }

            // Process incoming updates from the server.
            var matchEnded = false;

            while (!matchEnded)
            {
                // Wait to receive the next update from the server.
                var eventJson = await _socket.RecvStringAsync(_cancellation.Token);

                // Feed the incoming event into the server state.
                IMatchEvent update = _serverState.HandleEvent(eventJson);

                // Apply the received update to the local state, updating both the game
                // state tracking and the visual state.
                switch (update)
                {
                case MatchEvent.TileDrawn draw:
                {
                    // Update the game state tracking for the client.
                    if (!_localState.TryDrawTile(draw.Seat))
                    {
                        // TODO: Handle the client being out of sync with the server.
                        throw new NotImplementedException("Client out of sync with server");
                    }

                    var localDraw = _localState.CurrentDraw(draw.Seat);
                    Debug.Assert(
                        draw.Tile.Element0 == localDraw.Id.Element0,
                        "Drew incorrect tile when simulating locally",
                        this);

                    // Update the visuals based on the draw event.
                    var hand       = _hands[(int)draw.Seat];
                    var tileObject = InstantiateTile(localDraw);
                    hand.DrawTile(tileObject);

                    // TODO: Do some kind of actual animation for the draw.

                    // If the local player was the one that drew the tile, have them discard a
                    // tile now.
                    if (draw.Seat == _seat)
                    {
                        Debug.Assert(
                            _localState.CurrentTurn() == _seat,
                            "Player drew a tile but it's not their turn???");

                        await DiscardTile();
                    }
                    else
                    {
                        // TODO: Remove the explicit delay once we have an animation for the
                        // draw.
                        await UniTask.Delay((int)(_delayAfterDraw * 1000));
                    }
                }
                break;

                case MatchEvent.TileDiscarded discard:
                {
                    // If we performed a discard event locally, the next discard event from
                    // the server should match the one we performed. Verify that's the case
                    // and reconcile our local state with the server state.
                    //
                    // Otherwise, perform the action on the local state and then verify that
                    // the local state is still in sync with the server state.
                    if (_lastDiscard is TileId lastDiscard)
                    {
                        if (discard.Seat != _seat ||
                            discard.Tile.Element0 != lastDiscard.Element0)
                        {
                            throw new OutOfSyncException(
                                      $"Previously discarded tile {lastDiscard}, but received" +
                                      $"discard event {discard}");
                        }

                        // Clear local tracking for discarded tile now that the server has
                        // caught up.
                        _lastDiscard = null;
                    }
                    else if (_localState.TryDiscardTile(discard.Seat, discard.Tile))
                    {
                        // Perform the discard action locally.
                        var hand = _hands[(int)discard.Seat];
                        hand.MoveToDiscard(discard.Tile);

                        // TODO: Remove the explicit delay once we have a proper animation.
                        await UniTask.Delay((int)(_delayAfterDiscard * 1000));
                    }
                    else
                    {
                        throw new OutOfSyncException($"Could not apply discard event locally: {discard}");
                    }

                    // TODO: Reconcile our local state with the updated server state to
                    // verify that the two are in sync.
                }
                break;

                case MatchEvent.MatchEnded _:
                {
                    matchEnded = true;
                }
                break;
                }
            }

            // Display that the match ended UI and wait for the player to hit the exit button.
            _matchEndedDisplayRoot.SetActive(true);
            await _exitButton.OnClickAsync(_cancellation.Token);

            // Exit the match, indicating that we should return to the home screen.
            return(NextScreen.Home);

            // Helper method to handle requesting match creation from the server.
            async UniTask RequestStartMatch(CancellationToken cancellation = default)
Exemple #18
0
    private void OnButtonFertilizerClick(TypeFertilizer typeFertilizer)
    {
        CSWareHouseStruct currFertilizerData = null;

        switch (typeFertilizer)
        {
        case TypeFertilizer.fertilizer2:
            currFertilizerData = StaticData.GetFertilizerCountByWhich(1);    //第二种化肥
            break;

        case TypeFertilizer.fertilizer3:
            currFertilizerData = StaticData.GetFertilizerCountByWhich(2);    //第二种化肥
            break;

        default:
            break;
        }
        if (currFertilizerData.GoodNum <= 0)
        {
            //关闭UI
            uiWorldHandleManager.SetHandleTileUIClose();
            string FertilizerName = StaticData.GetMultiLanguageByGameItemId(currFertilizerData.GoodId);
            string Tips           = string.Format(StaticData.GetMultilingual(120068), FertilizerName);
            StaticData.OpenCommonTips(Tips, 120010, async() =>
            {
                //跳转商城
                await StaticData.OpenShopUI(1);
            });
            return;
        }
        CSFertilizer csFertilizer = new CSFertilizer()
        {
            SoilId       = seedGrowComponent.tileComponent.SoilId,
            FertilizerId = currFertilizerData.GoodId
        };

        ManorProtocalHelper.UseFertilizer(csFertilizer, async(succ) =>
        {
            //关闭UI
            uiWorldHandleManager.SetHandleTileUIClose();
            //施肥特效
            string iconFretilizer = string.Empty;
            int propId            = csFertilizer.FertilizerId;
            iconFretilizer        = StaticData.configExcel.GetGameItemByID(propId).Icon;
            uiWorldHandleManager.uiFertilizerEffectComponent.ShowInfo(iconFretilizer);
            uiWorldHandleManager.uiFertilizerEffectComponent.GetComponent <RectTransform>().anchoredPosition = StaticData.ManorWorldPointToUICameraAnchorPos(seedGrowComponent.tileComponent.transform.position);
            uiWorldHandleManager.uiFertilizerEffectComponent.gameObject.SetActive(true);
            uiWorldHandleManager.isFertiliezeringAnimPlay = true;
            await UniTask.Delay(1000);
            uiWorldHandleManager.uiFertilizerEffectComponent.gameObject.SetActive(false);
            uiWorldHandleManager.isFertiliezeringAnimPlay = false;
            //end 施肥特效
            SeedGrowComponent.PeriodGrow nextPeriod = SeedGrowComponent.PeriodGrow.Seed;
            var remainTime = seedGrowComponent.remainTime - StaticData.GetFertilizerAddTimeMilliSeconds(currFertilizerData.GoodId) / 1000f;
            if (remainTime <= 0)
            {
                //下一个时期
                switch (seedGrowComponent.currCropPeriod)
                {
                case SeedGrowComponent.PeriodGrow.Seed:
                    nextPeriod = SeedGrowComponent.PeriodGrow.Germinate;
                    break;

                case SeedGrowComponent.PeriodGrow.Germinate:
                    nextPeriod = SeedGrowComponent.PeriodGrow.GrowUp;
                    //成长期减去对应的时间
                    remainTime = StaticData.GetSeedGrowComponentTotalSecond(seedGrowComponent, nextPeriod) + remainTime;
                    if (remainTime <= 0)
                    {
                        //跳过了成长期,直接到成熟期
                        remainTime = 0f;
                        nextPeriod = SeedGrowComponent.PeriodGrow.Ripe;
                    }
                    break;

                case SeedGrowComponent.PeriodGrow.GrowUp:
                    nextPeriod = SeedGrowComponent.PeriodGrow.Ripe;
                    break;

                case SeedGrowComponent.PeriodGrow.Ripe:
                    //如果成熟阶段继续施肥还是成熟阶段
                    nextPeriod = SeedGrowComponent.PeriodGrow.Ripe;
                    break;
                }
            }
            else
            {
                nextPeriod = seedGrowComponent.currCropPeriod;
            }

            seedGrowComponent.SetPeriod(nextPeriod, (long)remainTime * 1000);
            //化肥数量-1
            StaticData.UpdateFertilizerMinus1(currFertilizerData.GoodId);
        }, (error) =>
        {
            //关闭UI
            uiWorldHandleManager.SetHandleTileUIClose();
        });
    }
    public void LoadEvent(EventMeta meta)
    {
        async UniTask LoadCover(CancellationToken token)
        {
            Assert.IsNotNull(meta.cover);

            var tasks = new List <UniTask>();

            if (coverImage.sprite != null)
            {
                coverImage.DOKill();
                coverImage.DOColor(Color.black, 0.4f);
                tasks.Add(UniTask.Delay(TimeSpan.FromSeconds(0.4f), cancellationToken: token));
            }

            Sprite sprite = null;

            tasks.Add(Context.AssetMemory.LoadAsset <Sprite>(meta.cover.OriginalUrl, AssetTag.EventCover, cancellationToken: token).ContinueWith(result => sprite = result));

            try
            {
                await tasks;
            }
            catch (OperationCanceledException)
            {
                return;
            }

            coverImage.sprite = sprite;
            coverImage.FitSpriteAspectRatio();
            coverImage.DOColor(Color.white, 2f).SetDelay(0.8f);
        }

        async UniTask LoadLogo(CancellationToken token)
        {
            Assert.IsNotNull(meta.logo);

            var tasks = new List <UniTask>();

            if (logoImage.sprite != null)
            {
                logoImage.DOKill();
                logoImage.DOFade(0, 0.4f);
                tasks.Add(UniTask.Delay(TimeSpan.FromSeconds(0.4f), cancellationToken: token));
            }

            Sprite sprite = null;

            tasks.Add(Context.AssetMemory.LoadAsset <Sprite>(meta.logo.OriginalUrl, AssetTag.EventLogo, cancellationToken: token).ContinueWith(result => sprite = result));

            try
            {
                await tasks;
            }
            catch (OperationCanceledException)
            {
                return;
            }

            logoImage.sprite = sprite;
            logoImage.DOFade(1, 0.8f).SetDelay(0.4f);
        }

        AddTask(LoadCover);
        AddTask(LoadLogo);

        Context.Player.Settings.SeenEvents.Add(meta.uid);
        Context.Player.SaveSettings();

        infoBanner.Leave(onComplete: () =>
        {
            if (!Context.Player.Settings.ReadEventDetails.Contains(meta.uid))
            {
                viewDetailsNotification.Show();
            }
            viewDetailsButton.onPointerClick.SetListener(_ =>
            {
                Context.Player.Settings.ReadEventDetails.Add(meta.uid);
                Context.Player.SaveSettings();
                viewDetailsNotification.Hide();
                if (meta.url.IsNullOrEmptyTrimmed())
                {
                    Application.OpenURL($"{Context.WebsiteUrl}/posts/{meta.uid}");
                }
                else
                {
                    WebViewOverlay.Show(meta.url,
                                        onFullyShown: () =>
                    {
                        LoopAudioPlayer.Instance.FadeOutLoopPlayer();
                    },
                                        onFullyHidden: async() =>
                    {
                        AudioSettings.Reset(AudioSettings.GetConfiguration());
                        Context.AudioManager.Dispose();
                        Context.AudioManager.Initialize();
                        await UniTask.DelayFrame(5);
                        LoopAudioPlayer.Instance.Apply(it =>
                        {
                            it.FadeInLoopPlayer();
                            it.PlayAudio(it.PlayingAudio, forceReplay: true);
                        });
                    });
                }
            });
            const string dateFormat = "yyyy/MM/dd HH:mm";
            durationText.text       = (meta.startDate.HasValue ? meta.startDate.Value.LocalDateTime.ToString(dateFormat) : "")
                                      + "~"
                                      + (meta.endDate.HasValue ? meta.endDate.Value.LocalDateTime.ToString(dateFormat) : "");
            enterButton.onPointerClick.SetListener(_ =>
            {
                if (meta.locked)
                {
                    Context.Haptic(HapticTypes.Failure, true);
                    // TODO
                    return;
                }
                Context.Haptic(HapticTypes.SoftImpact, true);
                if (meta.levelId != null)
                {
                    SpinnerOverlay.Show();

                    RestClient.Get <OnlineLevel>(new RequestHelper
                    {
                        Uri = $"{Context.ApiUrl}/levels/{meta.levelId}"
                    }).Then(level =>
                    {
                        Context.ScreenManager.ChangeScreen(
                            GamePreparationScreen.Id, ScreenTransition.In, 0.4f,
                            transitionFocus: GetComponent <RectTransform>().GetScreenSpaceCenter(),
                            payload: new GamePreparationScreen.Payload {
                            Level = level.ToLevel(LevelType.User)
                        }
                            );
                    }).CatchRequestError(error =>
                    {
                        Debug.LogError(error);
                        Dialog.PromptAlert("DIALOG_COULD_NOT_CONNECT_TO_SERVER".Get());
                    }).Finally(() => SpinnerOverlay.Hide());
                }
                else if (meta.collectionId != null)
                {
                    Context.ScreenManager.ChangeScreen(
                        CollectionDetailsScreen.Id, ScreenTransition.In, 0.4f,
                        transitionFocus: GetComponent <RectTransform>().GetScreenSpaceCenter(),
                        payload: new CollectionDetailsScreen.Payload
                    {
                        CollectionId = meta.collectionId, Type = LevelType.User
                    }
                        );
                }
            });
            infoBanner.transform.RebuildLayout();
            infoBanner.Enter();
        });
    }
Exemple #20
0
 public async UniTask SavePosition(Vector2 position)
 {
     await UniTask.Delay(TimeSpan.FromSeconds(.5f));
 }
Exemple #21
0
        private async UniTaskVoid CooldownAsync(CancellationToken token = default)
        {
            await UniTask.Delay(TimeSpan.FromSeconds(characterCore.Alliance == CharacterType.Enemy ? WeaponRangedPara.WaitTime *EnemyWeaponRateLimit : WeaponRangedPara.WaitTime), cancellationToken : token);

            CanShot = true;
        }
Exemple #22
0
        // Start()メソッドをUniTaskVoidにしても問題なく動く
        private async UniTaskVoid Start()
        {
            await UniTask.Delay(TimeSpan.FromSeconds(10));

            Destroy(gameObject);
        }
Exemple #23
0
    // Start is called before the first frame update
    private async void Start()
    {
        await UniTask.Delay(TimeSpan.FromSeconds(animaciones.GetClip("MenuPrincipalAparecer").length));

        SceneManager.LoadScene(1);
    }
        public IEnumerator UnitySetUp() => UniTask.ToCoroutine(async() =>
        {
            Console.WriteLine($"[MirageTest] UnitySetUp class:{TestContext.CurrentContext.Test.ClassName} method:{TestContext.CurrentContext.Test.MethodName} ");

            serverGo      = new GameObject("server", typeof(ServerObjectManager), typeof(NetworkServer));
            clientGo      = new GameObject("client", typeof(ClientObjectManager), typeof(NetworkClient));
            socketFactory = serverGo.AddComponent <TestSocketFactory>();

            server = serverGo.GetComponent <NetworkServer>();
            client = clientGo.GetComponent <NetworkClient>();

            if (ServerConfig != null)
            {
                server.PeerConfig = ServerConfig;
            }
            if (ClientConfig != null)
            {
                client.PeerConfig = ClientConfig;
            }

            server.SocketFactory = socketFactory;
            client.SocketFactory = socketFactory;

            serverObjectManager        = serverGo.GetComponent <ServerObjectManager>();
            serverObjectManager.Server = server;

            clientObjectManager        = clientGo.GetComponent <ClientObjectManager>();
            clientObjectManager.Client = client;

            ExtraSetup();

            // wait 2 frames for start to be called
            await UniTask.DelayFrame(2);

            // create and register a prefab
            playerPrefab = new GameObject("player (unspawned)", typeof(NetworkIdentity), typeof(T));
            // DontDestroyOnLoad so that "prefab" wont be destroyed by scene loading
            // also means that NetworkScenePostProcess will skip this unspawned object
            Object.DontDestroyOnLoad(playerPrefab);

            var identity        = playerPrefab.GetComponent <NetworkIdentity>();
            identity.PrefabHash = Guid.NewGuid().GetHashCode();
            clientObjectManager.RegisterPrefab(identity);

            // wait for client and server to initialize themselves
            await UniTask.Delay(1);

            // start the server
            var started = new UniTaskCompletionSource();
            server.Started.AddListener(() => started.TrySetResult());
            server.StartServer();

            await started.Task;

            if (AutoConnectClient)
            {
                // now start the client
                client.Connect("localhost");

                await AsyncUtil.WaitUntilWithTimeout(() => server.Players.Count > 0);

                // get the connections so that we can spawn players
                serverPlayer = server.Players.First();
                clientPlayer = client.Player;

                // create a player object in the server
                serverPlayerGO      = Object.Instantiate(playerPrefab);
                serverPlayerGO.name = "player (server)";
                serverIdentity      = serverPlayerGO.GetComponent <NetworkIdentity>();
                serverComponent     = serverPlayerGO.GetComponent <T>();
                serverObjectManager.AddCharacter(serverPlayer, serverPlayerGO);

                // wait for client to spawn it
                await AsyncUtil.WaitUntilWithTimeout(() => clientPlayer.HasCharacter);

                clientIdentity      = clientPlayer.Identity;
                clientPlayerGO      = clientIdentity.gameObject;
                clientPlayerGO.name = "player (client)";
                clientComponent     = clientPlayerGO.GetComponent <T>();
            }

            await LateSetup();
        });
 public virtual async UniTask Closeing()
 {
     ViewUtility.RemoveAllButtonEvent(this);
     await UniTask.Delay(0);
 }
Exemple #26
0
    async Task DelayTransition()
    {
        await UniTask.Delay(TimeSpan.FromSeconds(3));

        uiStack.DoTransition(_toGreenPanel, Color.green);
    }
Exemple #27
0
    public async UniTask <int> CheckCurrentTutor()
    {
        if (Services.data.tutorStep != 0)
        {
            return(1);
        }

        int swipeStep = Services.data.swipeCount;

        head.SetActive(swipeStep >= 0);
        actionPanel.SetActive(false);
        enemyHP.SetActive(swipeStep > 0);
        myHP.SetActive(swipeStep > 1);
        myEnergy.SetActive(swipeStep > 0);
        unitPanel.SetActive(swipeStep >= 3);
        tutorText.SetActive(swipeStep < 2);



        if (swipeStep == 0)
        {
            myEnergy.SetActive(false);
            myHP.SetActive(false);
            tutorText.SetActive(false);

            head.GetComponent <EnemyHead> ().SetCustomEmotion("emotion1");

            RectTransform rectTransform = head.GetComponent <RectTransform> ();
            float         _y            = rectTransform.anchoredPosition.y;
            rectTransform.anchoredPosition = new Vector2(rectTransform.anchoredPosition.x, 400);
            await rectTransform.DOAnchorPosY(_y, 0.8f, false).AsyncWaitForCompletion();

            await UniTask.Delay(500);

            head.GetComponent <EnemyHead> ().SetCustomEmotion("emotion4");
            await rectTransform.DOShakeAnchorPos(1f, new Vector3 (0, 22, 0), 13, 89, true, false).AsyncWaitForCompletion();

            rectTransform.DOKill(false);

            head.GetComponent <EnemyHead> ().SetCustomEmotion("emotion1");
            enemyHP.SetActive(true);
            tutorText.SetActive(true);
            tutorText.GetComponent <CanvasGroup>().alpha = 0;

            CanvasGroup group = enemyHP.GetComponent <CanvasGroup> ();
            group.alpha = 0;
            await group.DOFade(1f, 0.7f).AsyncWaitForCompletion();

            group.DOKill();
        }
        else if (swipeStep == 1)
        {
            //enemyHP.SetActive (false);
            myHP.SetActive(true);

            CanvasGroup group = myHP.GetComponent <CanvasGroup> ();
            group.alpha = 0;
            await group.DOFade(1f, 0.7f).AsyncWaitForCompletion();

            group.DOKill();
        }

        return(1);
    }
Exemple #28
0
    /// <summary>
    /// 步骤切换
    /// </summary>
    /// <param name="index"></param>
    public async void StepCut(int index)
    {
        switch (index)
        {
        case 0:
            await ChapterTool.MoveUi(_oneIamgeRect, new Vector2(-490f, 0), 0.1f, 0.1f);

            await ChapterTool.FadeInFadeOut(_oneIamgeCanvasGroup, 0, fadeOut, null, () => { _oneIamgeRect.gameObject.SetActive(false); ClickBtn(); });

            //OpenClickBtn(true);
            break;

        case 1:
            _dialogueBase.Initial(() =>
            {
                Debug.Log("对话1完毕");
                //OpenClickBtn(true);
                _dialogueBase.Close();
                //_clickIndex = 2;
                ClickBtn();
                Debug.Log("_clickIndex:" + _clickIndex);
            }, TwoSceneSpeakBeforeCallBack, TwoSceneSpeakAfterCallBack);
            _dialogueBase.Show();
            //OpenClickBtn(false);
            break;

        case 2:
            //await ChapterTool.FadeInFadeOut(_twoImagCanvasGroup, 0, 0.1f, null, () =>
            //{
            _twoImagCanvasGroup.alpha = 0;
            _dialogueBoxTetragonumComponent.Initial(async() =>
            {
                await ChapterTool.FadeInFadeOut(_twoImagCanvasGroup, 1, fadeOut, new CancellationTokenSource(), () =>
                {
                    _therrBoxRect.gameObject.SetActive(false);
                    _dialogueBase.SetStartDialogueId(12000036);
                    _dialogueBase.Initial(() =>
                    {
                        ClickBtn();     //心想完成后直接下个画面
                        //OpenClickBtn(true);
                        _dialogueBase.Close();
                    });
                    _dialogueBase.Show();
                });
                _dialogueBoxTetragonumComponent.Close();
            }, SpeakBeforeAction, SpeakRearAction);
            _dialogueBoxTetragonumComponent.Show();
            //OpenClickBtn(false);
            //_dialogueBoxTetragonumComponent.OpenClickBtn(false);
            //});
            break;

        case 3:
            await ChapterTool.FadeInFadeOut(_twoImagCanvasGroup, 0, fadeOut, null, () => { _twoImagCanvasGroup.gameObject.SetActive(false); });

            _dialogueBaseTwo.Initial(() =>
            {
                _dialogueBaseTwo.Close();
                Debug.Log("对话2完毕");
                ChapterTool.MoveUi(_bgTwoRect, new Vector3(-737, 0, 0), 0.8f, 0.2f);
                ChapterTool.ChangeUiSize(_bgTwoRect, new Vector3(2737, 5808, 1), 90, 10, null, () =>
                {
                    _phoneBtn.enabled = true;
                    _phoneBtn.transform.GetComponent <Image>().enabled = true;
                    _phoneBtn.transform.Find("ChapterClickGuidance").gameObject.SetActive(true);
                });
            }, SpeakAeforeActionTwo, SpeakRearActionTwo, SpeakBoxCloseActionTwo);
            _dialogueBaseTwo.Show();
            Debug.Log("对话2初始化完毕");
            break;

        case 4:
            Debug.Log("第四步");

            await _dialogueBaseTwo.CloseAllShowText();

            await UniTask.WaitUntil(() => _dialogueBaseTwo.IsAllClose(0));

            await UniTask.Delay(TimeSpan.FromSeconds(1));

            _dialogueBaseTwo.MomentCloseOrOpen(true);
            _dialogueBaseTwo.OpenClickBtn(false);
            _dialogueBaseTwo.gameObject.SetActive(false);
            ChapterTool.FadeInFadeOut(_fourCanvasGroup, 1, fadeOut, new CancellationTokenSource());
            await ChapterTool.FadeInFadeOut(_twoImagCanvasGroup, 0, fadeOut, null, () =>
            {
                _twoImageRect.gameObject.SetActive(false);
                _chapterGuidance.gameObject.SetActive(true);
                _chapterGuidance.PlayGuidanceAnima(_chapterGuidance.transform.localPosition, new Vector3(-40, 247));
            });

            break;

        case 5:
            ChapterTool.FadeInFadeOut(_cupCanvasGroup, 0, fadeOut, null, () => { _cupRect.gameObject.SetActive(false); });
            await ChapterTool.FadeInFadeOut(_bgtOneCanvasGroup, 0, fadeOut, new CancellationTokenSource(), () =>
            {
                _bgtOneCanvasGroup.gameObject.SetActive(false);
                _dialogueBaseTwo.gameObject.SetActive(true);
                _dialogueBaseTwo.MomentCloseOrOpen(false);
                _dialogueBaseTwo.OpenClickBtn(true);
                _dialogueBaseTwo.GetRoleData(10000001).SetRolePoint(new Vector3(24, 543));
                _dialogueBaseTwo.GetRoleData(10000002).SetRolePoint(new Vector3(0, -1550));
                _dialogueBaseTwo.ClickBtn();
            });

            break;

        case 6:
            _phoneBtn.enabled = false;
            await ChapterTool.FadeInFadeOut(_bgTwoCanvasGroup, 0, fadeOut, null, () => { _bgTwoRect.gameObject.SetActive(false); });

            break;

        case 7:
            OprnFour();
            break;

        case 8:
            _fiveBtnBoxRect.gameObject.SetActive(true);
            _fourRect.gameObject.SetActive(false);
            _answerThePhoneRect.gameObject.SetActive(false);
            break;
        }
    }
Exemple #29
0
 //好友庄园打开偷取列表
 public async UniTask PlayAnimFriendStealListToOpen()
 {
     DoTweenToPos(FriendBottom, new Vector2(FriendBottom.anchoredPosition.x, 281.02f));
     await UniTask.Delay((int)(timeLength * 1000));
 }
        /// <summary>
        ///     Connect to server.
        /// </summary>
        /// <returns></returns>
        public async UniTask ConnectAsync()
        {
            Options.ConnectionAddress.ToString(out string productId);

#if UNITY_EDITOR
            if (Logger.logEnabled)
#endif
            if (Transport.transportDebug)
            {
                DebugLogger.RegularDebugLog($"[Client] - attempting connection to {productId}");
            }

            if (_initialWait)
            {
                // This allows us to dump epic back end of filled up messages
                // after disconnecting from host.
                await UniTask.Delay(2 * 1000);

                _initialWait = false;
            }

            try
            {
                // Send a message to server to initiate handshake connection
                SendInternal(Options.ConnectionAddress, InternalMessage.Connect, SocketName);

                _connectedComplete = AutoResetUniTaskCompletionSource.Create();

                while (
                    await UniTask.WhenAny(_connectedComplete.Task,
                                          UniTask.Delay(TimeSpan.FromSeconds(Math.Max(1, Options.ConnectionTimeOut)))) != 0)
                {
#if UNITY_EDITOR
                    if (Logger.logEnabled)
#endif
                    if (Transport.transportDebug)
                    {
                        DebugLogger.RegularDebugLog(
                            $"[Client] - Connection to {productId} timed out.", LogType.Error);
                    }

                    Error.Invoke(Result.LobbyInviteFailed,
                                 $"[Client] - Connection to {productId} timed out.");

                    Disconnect();

                    return;
                }

                // Everything went good let's just return.
                // We need to switch to main thread for some reason.
                await UniTask.SwitchToMainThread();
            }
            catch (FormatException)
            {
                Error?.Invoke(Result.InvalidProductUserID,
                              $"[Client] - Connection string was not in the correct format.");

#if UNITY_EDITOR
                if (Logger.logEnabled)
#endif
                if (Transport.transportDebug)
                {
                    DebugLogger.RegularDebugLog(
                        "[Client] - Connection string was not in the right format. Did you enter a ProductId?",
                        LogType.Error);
                }
            }
            catch (Exception ex)
            {
                Error?.Invoke(Result.NotFound, $"Error: {ex.Message}");

#if UNITY_EDITOR
                if (Logger.logEnabled)
#endif
                if (Transport.transportDebug)
                {
                    DebugLogger.RegularDebugLog($"[Client] - Error: {ex.Message}", LogType.Error);
                }

                Disconnect();
            }
        }