void OnClickTestStart()
    {
        prevTime = Time.realtimeSinceStartup;

        for (int i = 0; i < count; ++i)
        {
            switch (coroutineType)
            {
            case CoroutineType.MonoBehaviourCoroutine:
                StartCoroutine(TestCoroutine());
                break;

            case CoroutineType.MainThreadCoroutine:
                MainThreadDispatcher.StartCoroutine(TestCoroutine());
                break;

            case CoroutineType.SendStartCoroutine:
                MainThreadDispatcher.SendStartCoroutine(TestCoroutine());
                break;

            case CoroutineType.MicroCoroutine:
                MainThreadDispatcher.StartUpdateMicroCoroutine(TestCoroutine());
                break;

            case CoroutineType.EndOfFrameMicroCoroutine:
                MainThreadDispatcher.StartEndOfFrameMicroCoroutine(TestCoroutine());
                break;

            case CoroutineType.FixedUpdateMicroCoroutine:
                MainThreadDispatcher.StartFixedUpdateMicroCoroutine(TestCoroutine());
                break;
            }
        }
    }
Example #2
0
        public static void create()
        {
            GameObject    terrain_gameobject = GameObject.FindWithTag(terrain_gameobject_name);
            TerrainConfig terrain_config     = TerrainConfigRepository.get(TerrainConfigRepository.createDefault());
            WorldConfig   world_config       = (SceneService.transition_scene_data as AllowWorldCreate).world_config;

            //Debug.Log("terrain_seed: " + world_config.terrain_seed);

            TerrainService.reset(terrain_gameobject, terrain_config, world_config);

            Debug.Log("TerrainFactory.create: TerrainService.createUnityTerrains: ");
            TerrainService.createUnityTerrains();

            Debug.Log("TerrainFactory.create: TerrainService.setupTerrainCollection: ");
            TerrainService.setupTerrainCollection();

            Observable.FromCoroutine(x =>
                                     TerrainService.update(0, 0)
                                     ).Subscribe(x => {
                MessageBroker.Default.Publish(new TerrainCreated {
                });
            });

            MessageBroker.Default.Receive <playerTerrainChunkMove>().Subscribe(x => {
                Debug.Log("TerrainFactory.create: " + x.x + ", " + x.z);
                MainThreadDispatcher.StartCoroutine(TerrainService.update(x.x, x.z));
            });
        }
Example #3
0
        public Coroutine StartCoroutine(IEnumerator enumerator)
        {
            var co = MainThreadDispatcher.StartCoroutine(enumerator);

            _coroutines.Add(co);
            return(co);
        }
Example #4
0
        // TODO: View manipulation should be only in Presenter.
        /// <summary>
        ///		Runs this test driver.
        /// </summary>
        /// <param name="buttonPrefab">The prefab for test starting buttons.</param>
        /// <param name="buttonVertical">The vertical area which test starting buttons to be belonging.</param>
        /// <param name="resultPrefab">The prefab for test result indicators.</param>
        /// <param name="resultVertical">The vertical area which test result indicators to be belonging.</param>
        public void Run(Button buttonPrefab, GameObject buttonVertical, Result resultPrefab, GameObject resultVertical)
        {
            // For all run.
            {
                var allButton = GameObject.Instantiate(buttonPrefab);
                allButton.GetComponentInChildren <Text>().text = "All(" + this.TestClasses.Sum(c => c.MethodCount).ToString("#,0", CultureInfo.CurrentCulture) + ")";
                allButton.OnClickAsObservable().Subscribe(_ =>
                {
                    Clear(resultVertical);
                    MainThreadDispatcher.StartCoroutine(RunAllTestCoroutine(this.TestClasses, resultPrefab, resultVertical));
                }
                                                          );
                allButton.transform.SetParent(buttonVertical.transform, true);
            }

            foreach (var item in this.TestClasses)
            {
                var testClass = item;
                var button    = GameObject.Instantiate(buttonPrefab);
                button.GetComponentInChildren <Text>().text = testClass.Name + "(" + testClass.MethodCount.ToString("#,0", CultureInfo.CurrentCulture) + ")";
                button.OnClickAsObservable().Subscribe(_ =>
                {
                    Clear(resultVertical);
                    MainThreadDispatcher.StartCoroutine(RunTestCoroutine(testClass, resultPrefab, resultVertical));
                }
                                                       );
                button.transform.SetParent(buttonVertical.transform, true);
            }
        }
Example #5
0
        public void Run()
        {
            // MainThreadDispatcher is heart of Rx and Unity integration

            // StartCoroutine can start coroutine besides MonoBehaviour.
            MainThreadDispatcher.StartCoroutine(TestAsync());

            // We have two way of run coroutine, FromCoroutine or StartCoroutine.
            // StartCoroutine is Unity primitive way and it's awaitable by yield return.
            // FromCoroutine is Rx, it's composable and cancellable by subscription's IDisposable.
            // FromCoroutine's overload can have return value, see:Sample05_ConvertFromCoroutine
            Observable.FromCoroutine(TestAsync).Subscribe();

            // Add Action to MainThreadDispatcher. Action is saved queue, run on next update.
            MainThreadDispatcher.Post(_ => Debug.Log("test"), null);

            // Timebased operations is run on MainThread(as default)
            // All timebased operation(Interval, Timer, Delay, Buffer, etc...)is single thread, thread safe!
            Observable.Interval(TimeSpan.FromSeconds(1))
            .Subscribe(x => Debug.Log(x));

            // Observable.Start use ThreadPool Scheduler as default.
            // ObserveOnMainThread return to mainthread
            Observable.Start(() => Unit.Default) // asynchronous work
            .ObserveOnMainThread()
            .Subscribe(x => Debug.Log(x));
        }
Example #6
0
            // \IDisposable

            // IGameTask

            public void Start()
            {
                if (Complete.Value || _loadRoutine != null || _isDisposed)
                {
                    return;
                }
                _loadRoutine = MainThreadDispatcher.StartCoroutine(GetAssetBundle(BundleUrl, _description.Hash128));
            }
Example #7
0
 public override void OnCompleted()
 {
     if (coroutineKey.IsDisposed)
     {
         return;
     }
     MainThreadDispatcher.StartCoroutine(OnCompletedDelay());
 }
Example #8
0
#pragma warning restore 649

        // IGameService

        public void Initialize()
        {
            var manifestPath = $@"{Application.streamingAssetsPath}/Bundles/manifest.json";

#if UNITY_IOS
            manifestPath = $"file://{manifestPath}";
#endif
            MainThreadDispatcher.StartCoroutine(LoadManifest(manifestPath));
        }
Example #9
0
            public override void OnNext(T value)
            {
                if (coroutineKey.IsDisposed)
                {
                    return;
                }

                MainThreadDispatcher.StartCoroutine(OnNextDelay(value));
            }
Example #10
0
        void Start()
        {
            _unit = GameState.Instance.Repository.Unit;
            _unit.Name.SubscribeToText(NameText);
            _unit.CanUpgrade.Subscribe(active => UpgradeButton.interactable = active);
            _unit.CurrentHp.Subscribe(_ => UpdateHealth());
            _unit.MaxHp.Subscribe(_ => UpdateHealth());
            _unit.IsDead.Subscribe(_ => UpdateHealth());

            _unit.UpgradeLevel.SkipLatestValueOnSubscribe().Subscribe(_ => MainThreadDispatcher.StartCoroutine(AnimateName()));
        }
        public void PreloadResources(List <ResourcesData> inBundleData)
        {
            if (inBundleData == null)
            {
                return;
            }

            //Unload all current bundles of this resources service
            UnloadResources();

            //Get AssetBundles
            MainThreadDispatcher.StartCoroutine(GetAssetBundles(inBundleData));
        }
        public void StartSystem(IGroupAccessor @group)
        {
            this.WaitForScene().Subscribe(x => _level = _levelAccessor.Entities.First());

            _updateSubscription = Observable.EveryUpdate().Where(x => IsLevelLoaded())
                                  .Subscribe(x => {
                if (_isProcessing)
                {
                    return;
                }
                MainThreadDispatcher.StartCoroutine(CarryOutTurns(@group));
            });
        }
        IEnumerator AssetBundlesUpdateStart()
        {
            string assetBundleServerPath = AssetBundlePathResolver.Instance.AssetBundleServerPath;
            string assetBundleLocalPath  = AssetBundlePathResolver.Instance.BundleCacheDir;

            yield return(MainThreadDispatcher.StartCoroutine(UpdateAssetBundle(assetBundleServerPath, assetBundleLocalPath)));

            if (!m_HasError)
            {
                AssetBundleUpdateCompleteEvent?.Invoke();
            }
            else
            {
                AssetBundleUpdateErrorEvent?.Invoke(deleteFolder);
            }
        }
        void IDispatcher.ExecuteAll(MainThreadDispatcher Owner)
        {
            foreach (var E in ExecutionQueue)
            {
                try
                {
                    Owner.StartCoroutine(E);
                }
                catch (Exception Ex)
                {
                    Debug.LogException(Ex);
                }
            }

            ExecutionQueue.Clear();
        }
Example #15
0
        public void Run()
        {
            // two way start coroutine beside mono
            MainThreadDispatcher.StartCoroutine(TestAsync());
            Observable.FromCoroutine(TestAsync).Subscribe();

            // 在非主线程执行主线程
            MainThreadDispatcher.Post(_ => print(_.ToString()), "gameplay");

            // 所有基于时间或者帧操作的函数主线程执行
            Observable.IntervalFrame(66).Subscribe(_ => print(_));

            // start()会开启新线程
            Observable.Start(() => Unit.Default)
            .ObserveOnMainThread()
            .Subscribe(_ => print(_), exception => print(exception.StackTrace));
        }
Example #16
0
        public void StartSystem(IGroupAccessor group)
        {
            _button.OnClickAsObservable()
            .Subscribe(x =>
            {
                _stopGlitch();
                _startButton.SetActive(false);
                _scene.allowSceneActivation = true;
            })
            .AddTo(_subscriptions);

            this.WaitForScene()
            .Subscribe(x =>
            {
                MainThreadDispatcher.StartCoroutine(_loadingScene("Game"));
            });
        }
Example #17
0
    private void SetGraphUp()
    {
        if (AstarPath.active == null)
        {
            throw new System.Exception("There is no AstarPath object in the scene");
        }

        var graph = AstarPath.active.data.gridGraph;

        if (graph == null)
        {
            throw new System.Exception("The AstarPath object has no GridGraph or LayeredGridGraph");
        }

        graph.SetDimensions(_levelData.Field.Width, _levelData.Field.Depth, graph.nodeSize);
        graph.center = Vector3.zero;

        MainThreadDispatcher.StartCoroutine(Scanner());
    }
Example #18
0
 IEnumerator flyToMaxPosition()
 {
     while (true)
     {
         if (!Config.IsPaused)
         {
             if (maxPosition < enemies.position.x)
             {
                 MainThreadDispatcher.StartCoroutine(flyToMinPosition());
                 enemies.Translate(Vector3.down / 3);
                 break;
             }
             if (!Config.IsPaused)
             {
                 enemies.Translate(Vector3.right * Time.deltaTime * speed);
             }
         }
         yield return(true);
     }
 }
Example #19
0
        private void _createExplosion(IEntity source)
        {
            if (!source.HasComponent <ViewComponent>())
            {
                return;
            }

            var viewComponent = source.GetComponent <ViewComponent>();
            var go            = viewComponent.View.gameObject;
            var startPosition = go.transform.position;

            var explosionComponent = new ExplosionComponent()
            {
                startPosition = startPosition
            };
            var entity = _pool.CreateEntity();

            entity.AddComponent(explosionComponent);
            entity.AddComponent(new ViewComponent());

            MainThreadDispatcher.StartCoroutine(_removeExplosion(entity));
        }
        private IEnumerator DownLoadAssetBundles(List <string> assetBundles, string assetBundleServerPath,
                                                 string assetBundleLocalPath)
        {
            int currentCount = 0;

            for (int i = 0; i < assetBundles.Count; i++)
            {
                string assetBundleName = assetBundles[i];

                string serverAssetBundlesPath = string.Format("{0}/{1}", assetBundleServerPath, assetBundleName);

                string localAssetBundlesPath = string.Format("{0}/{1}", assetBundleLocalPath, assetBundleName);

                yield return(MainThreadDispatcher.StartCoroutine(DownLoadAssetBundle(serverAssetBundlesPath, localAssetBundlesPath)));

                if (m_HasError)
                {
                    deleteFolder = true;
                    yield break;
                }

                currentCount++;
            }
        }
Example #21
0
    //壁を生成する
    private void CreateWalls()
    {
        Debug.Log("CreateWalls");

        Model.Walls = new List <Vector3>();
        for (int i = 1; i < 100; i++)
        {
            //x座標は20m間隔
            float x = i * 20f;
            x += Random.Range(-5f, 5f);

            //y座標は0 or 10
            float y = 0;
            if (Random.value > 0.5f)
            {
                y = 10f;
            }

            Vector3 position = new Vector3(x, y, 0f);
            Model.Walls.Add(position);
        }

        MainThreadDispatcher.StartCoroutine(UpdateWallsNextFrame());
    }
Example #22
0
    public void LateInitialize()
    {
        if (ShouldLoginImmediately)
        {
            Login();
            ShouldLoginImmediately = false;
        }
        if (base.Inited)
        {
            Singleton <CloudSyncRunner> .Instance.CloudSync("init_pf");

            return;
        }
        UniRx.IObservable <bool> first = from should in ConnectivityService.InternetConnectionAvailable.CombineLatest(PlayerData.Instance.LifetimePrestiges, (bool net, int prestiges) => net && string.IsNullOrEmpty(LoggedOnPlayerId.Value) && prestiges > 0)
                                         where should
                                         select should;

        UniRx.IObservable <bool> observable = from should in ConnectivityService.InternetConnectionAvailable.CombineLatest(PersistentSingleton <FacebookAPIService> .Instance.IsLoggedToFB, (bool net, bool fb) => net && fb)
                                              where should
                                              select should;

        first.Merge(observable).Subscribe(delegate
        {
            Login();
        });
        MainThreadDispatcher.StartCoroutine(QueueRoutine());
        (from chunk in PlayerData.Instance.LifetimeChunk
         select(chunk != 0) ? Observable.Never <bool>() : m_hasCommandsInFlight.AsObservable()).Switch().Subscribe(delegate(bool inFlight)
        {
            if (BindingManager.Instance != null)
            {
                BindingManager.Instance.SystemPopup.SetActive(inFlight);
            }
        });
        LoggedOnPlayerId.Subscribe(delegate(string loggedID)
        {
            PlayerData.Instance.PFId.Value = loggedID;
        });
        LoggedOnPlayerId.CombineLatest(PlayerData.Instance.DisplayName, (string id, string dn) => dn).Subscribe(delegate(string name)
        {
            PlayFabService playFabService = this;
            GetAccountInfo(delegate(JSONObject json)
            {
                string a = json.asJSONObject("AccountInfo").asJSONObject("TitleInfo").asString("DisplayName", () => string.Empty);
                if (name != string.Empty && a != name)
                {
                    playFabService.UpdateUserDisplayName(name, null, null);
                }
                else if (name == string.Empty && a == string.Empty)
                {
                    (from fbname in Singleton <FacebookRunner> .Instance.PlayerName.AsObservable().Take(1)
                     where !string.IsNullOrEmpty(fbname)
                     select fbname).Subscribe(delegate(string fbname)
                    {
                        playFabService.UpdateUserDisplayName(fbname, null, null);
                    });
                }
            }, null);
        });
        base.Inited = true;
    }
        IEnumerator UpdateAssetBundle(string assetBundleServerPath, string assetBundleLocalPath)
        {
            string localAssetBundleManifestPath  = $"{assetBundleLocalPath}/{AssetBundlePathResolver.Instance.BundleSaveDirName}";
            string serverAssetBundleManifestPath = $"{assetBundleServerPath}/{AssetBundlePathResolver.Instance.BundleSaveDirName}";

            string localDependFilePath  = $"{assetBundleLocalPath}/{AssetBundlePathResolver.Instance.DependFileName}";
            string serverDependFilePath = $"{assetBundleServerPath}/{AssetBundlePathResolver.Instance.DependFileName}";

            AssetBundleManifest localAssetBundleManifest  = null;
            AssetBundleManifest serverAssetBundleManifest = null;

            if (FileUtility.CheckFileIsExist(localAssetBundleManifestPath) == false)
            {
                yield return(MainThreadDispatcher.StartCoroutine(DownLoadAssetBundle(serverAssetBundleManifestPath, localAssetBundleManifestPath)));

                if (m_HasError)
                {
                    deleteFolder = true;
                    yield break;
                }

                yield return(MainThreadDispatcher.StartCoroutine(DownLoadAssetBundle(serverDependFilePath, localDependFilePath)));

                if (m_HasError)
                {
                    deleteFolder = true;
                    yield break;
                }

                localAssetBundleManifest           = LoadLocalAssetBundleManifest(localAssetBundleManifestPath);
                m_NeedDownloadAssetBundleNamesList = localAssetBundleManifest.GetAllAssetBundles().ToList();
                int currentCount = 0;
                for (int i = 0; i < m_NeedDownloadAssetBundleNamesList.Count; i++)
                {
                    string assetBundleName = m_NeedDownloadAssetBundleNamesList[i];

                    string serverAssetBundlesPath = string.Format("{0}/{1}", assetBundleServerPath, assetBundleName);

                    string localAssetBundlesPath = string.Format("{0}/{1}", assetBundleLocalPath, assetBundleName);

                    yield return(MainThreadDispatcher.StartCoroutine(DownLoadAssetBundle(serverAssetBundlesPath, localAssetBundlesPath)));

                    if (m_HasError)
                    {
                        deleteFolder = true;
                        yield break;
                    }

                    currentCount++;
                    AssetBundleUpdateProcessEvent?.Invoke((float)currentCount / m_NeedDownloadAssetBundleNamesList.Count);
                }
            }
            else
            {
                byte[] localAssetBundleManifestBytes = FileUtility.FileConvertToBytes(localAssetBundleManifestPath);
                //load AssetBundleManifest to memory from server
                WWW serverWWW = new WWW(serverAssetBundleManifestPath);

                yield return(serverWWW);

                if (serverWWW.error != null)
                {
                    m_HasError = true;
                    yield break;
                }

                byte[] serverAssetBundleManifestBytes = serverWWW.bytes;
                serverWWW.Dispose();

                if (HashUtil.Get(localAssetBundleManifestBytes) == HashUtil.Get(serverAssetBundleManifestBytes))
                {
                    AssetBundleUpdateProcessEvent?.Invoke(1);
                    yield break;
                }

                yield return(MainThreadDispatcher.StartCoroutine(DownLoadAssetBundle(serverDependFilePath, localDependFilePath)));

                if (m_HasError)
                {
                    deleteFolder = true;
                    yield break;
                }

                serverAssetBundleManifest = LoadAssetBundleManifest(serverAssetBundleManifestBytes);
                localAssetBundleManifest  = LoadLocalAssetBundleManifest(localAssetBundleManifestPath);

                string[] localAssetBundleNames  = localAssetBundleManifest.GetAllAssetBundles();
                string[] serverAssetBundleNames = serverAssetBundleManifest.GetAllAssetBundles();

                ///Check each AssetBundles from server
                for (int i = 0; i < serverAssetBundleNames.Length; i++)
                {
                    string assetBundleName = serverAssetBundleNames[i];

                    if (localAssetBundleNames.Contains(assetBundleName))
                    {
                        Hash128 localAssetBundleHash = localAssetBundleManifest.GetAssetBundleHash(assetBundleName);

                        Hash128 serverAssetBundleHash = serverAssetBundleManifest.GetAssetBundleHash(assetBundleName);

                        //if the hash value is different,delete the AssetBundle file in local machine,then download the AssetBundle from server
                        if (localAssetBundleHash != serverAssetBundleHash)
                        {
                            m_NeedDownloadAssetBundleNamesList.Add(assetBundleName);
                        }
                    }
                    else
                    {
                        m_NeedDownloadAssetBundleNamesList.Add(assetBundleName);
                    }
                }

                //delete redundant AssetBundles in local machine
                for (int i = 0; i < localAssetBundleNames.Length; i++)
                {
                    string assetBundleName = localAssetBundleNames[i];

                    if (!serverAssetBundleNames.Contains(assetBundleName))
                    {
                        string deleteAssetBundlePath = string.Format("{0}/{1}", assetBundleLocalPath, assetBundleName);

                        //delete redundant AssetBundles
                        FileUtility.DeleteFile(deleteAssetBundlePath);
                        FileUtility.IfDeletedFileCurrentDirectoryIsEmptyDeleteRecursively(deleteAssetBundlePath);
                    }
                }
                int currentCount = 0;
                for (int i = 0; i < m_NeedDownloadAssetBundleNamesList.Count; i++)
                {
                    string assetBundleName = m_NeedDownloadAssetBundleNamesList[i];

                    string serverAssetBundlesPath = string.Format("{0}/{1}", assetBundleServerPath, assetBundleName);

                    string localAssetBundlesPath = string.Format("{0}/{1}", assetBundleLocalPath, assetBundleName);

                    yield return(MainThreadDispatcher.StartCoroutine(DownLoadAssetBundle(serverAssetBundlesPath, localAssetBundlesPath)));

                    if (m_HasError)
                    {
                        deleteFolder = true;
                        yield break;
                    }

                    currentCount++;
                    AssetBundleUpdateProcessEvent?.Invoke((float)currentCount / m_NeedDownloadAssetBundleNamesList.Count);
                }

                FileUtility.BytesConvertToFile(serverAssetBundleManifestBytes, localAssetBundleManifestPath);
            }
            AssetBundleUpdateProcessEvent?.Invoke(1);
            serverAssetBundleManifest = null;
            localAssetBundleManifest  = null;
            Resources.UnloadUnusedAssets();
        }
Example #24
0
 public static void Fire()
 {
     MainThreadDispatcher.StartCoroutine(Hoge());
 }
 /// <summary>
 /// start update AssetBundles
 /// </summary>
 public void StartUpdateAssetBundles()
 {
     MainThreadDispatcher.StartCoroutine(AssetBundlesUpdateStart());
 }
Example #26
0
 public void LoadScene(string sceneName)
 {
     MainThreadDispatcher.StartCoroutine(StartLoad(sceneName));
 }
Example #27
0
 public static void OnComplete(this AsyncOperation operation, Action callback)
 {
     MainThreadDispatcher.StartCoroutine(OnCompleteAsyncOperation(operation, callback));
 }
        public void DownloadByLabel(string label)
        {
            var downloadLabelData = RemoteLabels.FirstOrDefault(val => val.Label == label);

            MainThreadDispatcher.StartCoroutine(DownloadInner(downloadLabelData));
        }
 public void Synchronization(Action onComplete = null)
 {
     MainThreadDispatcher.StartCoroutine(SynchronizationAssets(onComplete));
 }
Example #30
0
 public static void ResetGame()
 {
     MainThreadDispatcher.StartCoroutine(ResetGameRoutine());
 }