Author: Sebastiaan Fehr ([email protected]) Date: March 2013 Summary: Creates MonoBehaviour instance through which static classes can call StartCoroutine. Description: Classes that do not inherit from MonoBehaviour, or static functions within MonoBehaviours are inertly unable to call StartCoroutene, as this function is not static and does not exist on Object. This Class creates a proxy though which StartCoroutene can be called, and destroys it when no longer needed.
예제 #1
0
 public void Query(
     string query, string sToken       = "",
     object variables                  = null,
     Action <GraphQLResponse> callback = null)
 {
     Coroutiner.StartCoroutine(SendRequest(query, variables, callback, sToken));
 }
예제 #2
0
 static Startup()
 {
     if (AppCenterEditorPrefsSO.Instance.PanelIsShown || !AppCenterEditorSDKTools.IsInstalled)
     {
         Coroutiner.StartCoroutine(OpenAppCenterServices());
     }
 }
예제 #3
0
    /// <summary>
    ///  Creates an instance of the current champion
    /// </summary>
    public void RunBest()
    {
        champRunning = true;
        NeatGenome genome = LoadChampion();

        // Get a genome decoder that can convert genomes to phenomes.
        var genomeDecoder = experiment.CreateGenomeDecoder();
        // Decode the genome into a phenome (neural network).
        var phenome = genomeDecoder.Decode(genome);

        InstantiateCandidate(phenome);
        GameObject bestInstance = ControllerMap[phenome].gameObject;

        // Special tag so we can selectively actuate on these units.
        bestInstance.tag = "BestUnit";
        // Also removes the tag from child components (but no granchildren. This
        // is currently ok since these elements have no coliders and champions
        // are destroyed before entering evolution).
        // These cannot use "BestUnit" or we will be in trouble when we destroy
        // the unit!
        foreach (Transform child in bestInstance.transform)
        {
            child.gameObject.tag = "Untagged";
        }

        // This is called if we want the champions to be evaluated, mostly for
        // research reasons.
        if (false)
        {
            Coroutiner.StartCoroutine(EvaluateChamp(phenome));
        }
    }
예제 #4
0
    internal static void Move(Place.ExitDirections direction)
    {
        if (CruiseControl.waitingForConfirmation)
        {
            return;
        }
        else
        {
            switch (direction)
            {
            case Place.ExitDirections.North:
                WoTUnityClient.Send("n\nexits");
                break;

            case Place.ExitDirections.East:
                WoTUnityClient.Send("e\nexits");
                break;

            case Place.ExitDirections.South:
                WoTUnityClient.Send("s\nexits");
                break;

            case Place.ExitDirections.West:
                WoTUnityClient.Send("w\nexits");
                break;
            }
            Player.me.attemptedMoveDirection = direction;
            CruiseControl.ConfirmationPending();
            Coroutiner.StartCoroutine(TimeoutMove());
        }
    }
    public void gameOver(bool fail = false)
    {
        isPlaying = false;
        Debug.Log("GAME FINISHED " + fail + " SCORE: " + score);
        PlayerPrefs.SetFloat("score", fail ? 0 : 10);
        PlayerPrefs.SetString("sceneName", "Bureaucracy");
        PlayerPrefs.SetInt("fail", fail ? 1 : 0);
        if (mySlider != null)
        {
            Destroy(mySlider.gameObject);
        }

        GameObject.Find("LineRenderer0").GetComponent <LineRenderer>().enabled = false;
        GameObject.Find("LineRenderer1").GetComponent <LineRenderer>().enabled = false;
        GameObject.Find("LineRenderer2").GetComponent <LineRenderer>().enabled = false;
        GameObject.Find("LineRenderer3").GetComponent <LineRenderer>().enabled = false;
        if (fail)
        {
            finalLostAnimation.SetActive(true);
        }
        else
        {
            finalWinAnimation.SetActive(true);
        }

        Coroutiner.StartCoroutine(NavigateToGameOver());
    }
예제 #6
0
 /// <summary>
 /// Starts the algorithm running. The algorithm will switch to the Running state from either
 /// the Ready or Paused states.
 /// </summary>
 public void StartContinue()
 {
     //print("StartContinue");
     // RunState must be Ready or Paused.
     if (RunState.Ready == _runState)
     {   // Create a new thread and start it running.
         //   print("RunState ready");
         _runState = RunState.Running;
         Coroutiner.StartCoroutine(AlgorithmThreadMethod());
         //   print("Continue from AlgorithmThreadMethod in StartContinue");
         OnUpdateEvent();
     }
     else if (RunState.Paused == _runState)
     {   // Thread is paused. Resume execution.
         _runState = RunState.Running;
         OnUpdateEvent();
         _awaitRestartEvent.Set();
     }
     else if (RunState.Running == _runState)
     {   // Already running. Log a warning.
         //__log.Warn("StartContinue() called but algorithm is already running.");
     }
     else
     {
         throw new SharpNeatException(string.Format("StartContinue() call failed. Unexpected RunState [{0}]", _runState));
     }
 }
예제 #7
0
    /// <summary>
    /// 下载版本文件
    /// </summary>
    /// <returns></returns>
    IEnumerator LoadVersion()
    {
        Logger.Log("LoadVersion url:" + PathUtils.versionUrl);
        WWW www = new WWW(PathUtils.versionUrl);

        yield return(www);

        if (string.IsNullOrEmpty(www.error) && www.isDone)
        {
            JArray jsonArr = (JArray)JsonConvert.DeserializeObject(www.text);
            foreach (JObject json in jsonArr)
            {
                string webVersion = json["localversion"].ToString();

                if (int.Parse(webVersion) == Version)
                {
                    url     = json["url"].ToString();
                    mapName = json["map"].ToString();
                    if (!string.IsNullOrEmpty(mapName))
                    {
                        Coroutiner.Start(DownMap());
                    }
                    else
                    {
                        Logger.LogError("LoadVersion error: mapName null!");
                    }
                    break;
                }
            }
        }
        else
        {
            Logger.LogError("LoadVersion error:" + www.error);
        }
    }
예제 #8
0
        private IEnumerator CreateNewTile(int pos, bool previousAllowTouch)
        {
            yield return(new WaitForSeconds(0.21f));

            bool createMore = false;

            for (int x = 0; x < matchTileGridModel.gridSize.x; x++)
            {
                float y = matchTileGridModel.gridSize.y - 1f;

                Vector2   tilePos   = new Vector2(x, y);
                MatchTile matchTile = matchTileGridModel.GetMatchTile(tilePos);

                if (matchTile == null)
                {
                    createMore = true;

                    matchTileFactory.CreateRandomMatchTile(tilePos);
                }
            }

            if (createMore)
            {
                loopEnumerator = CreateNewTile(pos, previousAllowTouch);
                Coroutiner.StartCoroutine(loopEnumerator);
            }
            else
            {
                AllowTouch(previousAllowTouch);
            }
        }
    public void gameOver(bool fail = false)
    {
        //DestroyImmediate(mySlider.gameObject,true);
        if (isPlaying)
        {
            isPlaying = false;
            Debug.Log("GAME FINISHED " + fail + " SCORE: " + score);
            PlayerPrefs.SetFloat("score", fail ? 0 : 10);
            PlayerPrefs.SetString("sceneName", "Networking");
            PlayerPrefs.SetInt("fail", fail ? 1 : 0);

            if (mySlider != null)
            {
                Destroy(mySlider.gameObject);
            }

            if (fail)
            {
                finalLostAnimation.SetActive(true);
            }
            else
            {
                finalWinAnimation.SetActive(true);
            }

            Coroutiner.StartCoroutine(NavigateToGameOver());
        }
    }
예제 #10
0
        private IEnumerator EvaluateInMainThread(IBlackBox[] boxes)
        {
            Debug.Log($"Evaluating in {Thread.CurrentThread.ManagedThreadId} thread");
            if (_agents == null)
            {
                _agents = new Agent.Abstract.AAgentController[boxes.Length];
                for (int i = 0; i < boxes.Length; i++)
                {
                    var obj = Coroutiner.Instantiate(_agentPrefab, _gameObject.transform);
                    _agents[i] = obj.GetComponent <Agent.Abstract.AAgentController>();
                }
            }

            for (int i = 0; i < boxes.Length; i++)
            {
                var ag = (Agent.NetworkController)_agents[i];
                ag.Net = boxes[i];
                ag.Reset(_gameObject.transform.position);
            }

            yield return(null);

            for (int i = 0; i < _tickPerEvalCount.Value; i++)
            {
                foreach (var item in _agents)
                {
                    item.Tick();
                }
                yield return(new WaitForFixedUpdate());
            }

            _fitnesses = CalculateFitness(_agents);
        }
예제 #11
0
 /// <summary>
 /// Starts the algorithm running. The algorithm will switch to the Running state from either
 /// the Ready or Paused states.
 /// </summary>
 public void StartContinue()
 {
     // RunState must be Ready or Paused.
     if (RunState.Ready == _runState)
     {
         // Create a new Coroutine and start it running.
         _runState = RunState.Running;
         Coroutiner.StartCoroutine(AlgorithmThreadMethod());
         OnUpdateEvent();
     }
     else if (RunState.Paused == _runState)
     {
         _runState = RunState.Running;
         OnUpdateEvent();
         _awaitRestartEvent.Set();
     }
     else if (RunState.Running == _runState)
     {
         // Already running. Log a warning.
         UnitySharpNEAT.Utility.Log("StartContinue() called but algorithm is already running");
     }
     else
     {
         throw new SharpNeatException(string.Format("StartContinue() call failed. Unexpected RunState [{0}]", _runState));
     }
 }
예제 #12
0
		private IEnumerator Remove()
		{
			yield return new WaitForSeconds (0.05f);

			if (matchTileQueue.Count > 0)
			{
				RemoveTile removeTile = matchTileQueue [0];
				List<MatchTile> matchTiles = removeTile.matchTiles;

				for (int i = 0; i < matchTiles.Count; i++)
				{					
					Remove (matchTiles[i], removeTile);
				}

				matchTileQueue.RemoveAt (0);

				loopEnumerator = Remove ();
				Coroutiner.StartCoroutine (loopEnumerator);
			}
			else
			{
				endEnumerator = End ();
				Coroutiner.StartCoroutine (endEnumerator);
			}
		}
예제 #13
0
 // Download an image using WWW from a given URL
 public static void LoadImgFromURL(string imgURL, Action <Texture> callback)
 {
     // Need to use a Coroutine for the WWW call, using Coroutiner convenience class
     Coroutiner.StartCoroutine(
         LoadImgEnumerator(imgURL, callback)
         );
 }
예제 #14
0
 public void Query(string query, object variables = null, Action <GraphQLResponse> callback = null)
 {
     if (FB.IsLoggedIn)
     {
         Coroutiner.StartCoroutine(SendRequest(query, variables, callback));
     }
 }
예제 #15
0
    /// <summary>
    /// This function coordinates the manual selection process
    /// </summary>
    /// <param name="genome_list">Genome list.</param>
    public void ManualSelection(IList <TGenome> given_genome_list)
    {
        genome_list = given_genome_list;

        // Resets the abort trigger!
        is_aborted = false;

        // First we copy the fitness values in case we want to abort,
        // then we set fitness to 0
        saved_fitness = CopyAndClear();
        // Here we will save the brains (which we will need to kill our units)
        if (unit_brains == null)
        {
            unit_brains = new IBlackBox[genome_list.Count];
        }
        // Then the user can choose the units that display a more interesting
        // behaviour. These will be marked to change their fitness value.
        // The new fitness values will be used to determine the next generation's population.
        // Resets the list for selected genomes.
        selected_genomes = new Dictionary <int, bool>();
        // Creates the units...
        WakeUp();
        // We call this function from coroutiner since it is an IEnumerator
        Coroutiner.StartCoroutine(ManualEvaluation());
        // Then units are killed and NeatEvolutionAlgorithm continues
        // creating the offspring!
        // Kill is called at the end of ManualEvaluation
    }
예제 #16
0
        /// <summary> Plays the currently active animation </summary>
        /// <param name="button"> The button reference </param>
        /// <param name="withSound"> If set to <c>true</c> [with sound] </param>
        /// <param name="onStartCallback"> Callback fired when the animation starts playing </param>
        /// <param name="onCompleteCallback"> Callback fired when the animation completed playing </param>
        public void PlayAnimation(UIButton button, bool withSound = true, UnityAction onStartCallback = null, UnityAction onCompleteCallback = null)
        {
            // ReSharper disable once SwitchStatementMissingSomeCases
            switch (ButtonAnimationType)
            {
            case ButtonAnimationType.Punch:
                if (PunchAnimation == null)
                {
                    return;
                }
                UIAnimator.StopAnimations(button.RectTransform, AnimationType.Punch);
                if (PunchAnimation.Move.Enabled)
                {
                    button.ResetPosition();
                }
                if (PunchAnimation.Rotate.Enabled)
                {
                    button.ResetRotation();
                }
                if (PunchAnimation.Scale.Enabled)
                {
                    button.ResetScale();
                }
                UIAnimator.MovePunch(button.RectTransform, PunchAnimation, button.StartPosition);       //play the move punch animation
                UIAnimator.RotatePunch(button.RectTransform, PunchAnimation, button.StartRotation);     //play the rotate punch animation
                UIAnimator.ScalePunch(button.RectTransform, PunchAnimation, button.StartScale);         //play the scale punch animation
                Coroutiner.Start(InvokeCallbacks(PunchAnimation, onStartCallback, onCompleteCallback));
                break;

            case ButtonAnimationType.State:
                if (StateAnimation == null)
                {
                    return;
                }
                UIAnimator.StopAnimations(button.RectTransform, AnimationType.State);
                UIAnimator.MoveState(button.RectTransform, StateAnimation, button.StartPosition);
                UIAnimator.RotateState(button.RectTransform, StateAnimation, button.StartRotation);
                UIAnimator.ScaleState(button.RectTransform, StateAnimation, button.StartScale);
                UIAnimator.FadeState(button.RectTransform, StateAnimation, button.StartAlpha);
                Coroutiner.Start(InvokeCallbacks(StateAnimation, onStartCallback, onCompleteCallback));
                break;

            case ButtonAnimationType.Animator:
                if (Animators == null || Animators.Count == 0)
                {
                    return;
                }
                foreach (AnimatorEvent animatorEvent in Animators)
                {
                    animatorEvent.Invoke();
                }
                break;
            }

            if (withSound)
            {
                OnTrigger.PlaySound();
            }
        }
예제 #17
0
 /// <summary>
 /// Used from UImanager to ask for the resetting of the last module in
 /// all genomes.
 /// This counts as a new generation!
 /// </summary>
 public void AskResetActiveModule()
 {
     uiManager.WriteToRecord("Reset");
     // Note this will not return the cameras to the editing menu.
     StopInteractiveEvolution();
     // Restart and reset (after allowing time to stop and remove old individuals!)
     Coroutiner.StartCoroutine(WaitResetStart());
 }
예제 #18
0
 public void TakeDamage(int value)
 {
     if (_Shield.IsDestroyed)
     {
         Coroutiner.Start(Explode());
     }
     _Shield.DecreaseEnergy(value);
 }
    public void CallGC()
    {
        if (_GCing)
        {
            return;
        }

        Coroutiner.Start(_ResourcesGC());
    }
예제 #20
0
    public static void GetItems(string uid)
    {
        Debug.Log($"#Firebase# Getting items from {LocalDataProvider.Instance.localManager.name} {uid}");
        string json     = LocalDataProvider.Instance.localManager.GetItemsJson();
        var    firebase = GameObject.Find("Firebase");

        Debug.Log($"#Firebase# Received items");
        Coroutiner.Start(SendMessageDelayed(firebase, "ReceiveItems", json));
    }
예제 #21
0
        private IEnumerator Loop()
        {
            yield return(new WaitForSeconds(0.05f));

            CheckIfEmptySpaceNearBy();

            enumerator = Loop();
            Coroutiner.StartCoroutine(enumerator);
        }
예제 #22
0
 private static Coroutiner GetInstance()
 {
     if (instance == null)
     {
         GameObject go = new GameObject("Coroutiner");
         instance = go.AddComponent <Coroutiner>();
     }
     return(instance);
 }
예제 #23
0
        /// <summary>
        /// Tests the internet connection.
        /// </summary>
        /// <returns>The internet connection.</returns>
        public static IEnumerator TestInternetConnection()
        {
            long  startTime     = 0;
            long  timeTaken     = 0;
            float maxTime       = 5.0F;
            float secondsToWait = 10F;

                        #if INTERNET_CHECK_USING_PING
            while (true)
            {
                yield return(Job.CreateAsCoroutine(
                                 ExecutePingCommand("74.125.224.72", maxTime,
                                                    time => {
                    Logger.Log("RECEIVED PING - " + time);
                    if (time < maxTime)
                    {
                        IsInternetReachable = true;
                        secondsToWait = 20F;
                    }
                    else
                    {
                        IsInternetReachable = false;
                        secondsToWait = 5F;
                    }
                })));

                yield return(new WaitForSeconds(secondsToWait));
            }
                        #else
            while (true)
            {
                startTime = DateTime.Now.Ticks;
                //Util.Logger.Log("START TICK - " + startTime);
                yield return(Coroutiner.StartCoroutine(
                                 Util.ExecuteGetCommand("http://www.google.com",
                                                        www => {
                    timeTaken = DateTime.Now.Ticks - startTime;
                    //Util.Logger.Log("END TICK - " + DateTime.Now.Ticks);
                    //Util.Logger.Log("TIME TAKEN - " + timeTaken);
                    if (!string.IsNullOrEmpty(www.error))
                    {
                        //Util.Logger.Log("ERROR - " + www.error);
                        IsInternetReachable = false;
                        secondsToWait = 5;
                    }
                    else
                    {
                        IsInternetReachable = true;
                        secondsToWait = 20;
                    }
                })));

                yield return(new WaitForSeconds(secondsToWait));
            }
                        #endif
        }
예제 #24
0
        public void Execute()
        {
            int tilesTouched = matchTileGridModel.tilesToReplace;

            bool previousAllowTouch = matchTileGridModel.allowTouch;

            matchTileGridModel.allowTouch = false;

            enumerator = CreateNewTile(tilesTouched, previousAllowTouch);
            Coroutiner.StartCoroutine(enumerator);
        }
예제 #25
0
    public void OnCompleteHeartAnimation(GameObject heart)
    {
        DestroyImmediate(heart);

        var lives = PlayerPrefs.GetInt("Lives");

        if (lives <= 0) //END GAME
        {
            Coroutiner.StartCoroutine(finishGame());
        }
    }
예제 #26
0
 public static void CheckLoginStatus()
 {
     if (LocalDataProvider.Instance.alreadyLogin)
     {
         var firebase = GameObject.Find("Firebase");
         var result   = new LoginResult {
             Id = "123", FormFilled = LocalDataProvider.Instance.FormFilled
         };
         Coroutiner.Start(SendMessageDelayed(firebase, "LoginSuccess", LitJson.JsonMapper.ToJson(result)));
     }
 }
예제 #27
0
        /// <summary>
        /// This function starts the real evolution, although the details of
        /// each generation are coded in PerformOneGneration, an abstract
        /// funtcion implemented in the corresponding evolution algorithm
        /// (for example, NeatEvolutionAlgorithm).
        /// </summary>
        private IEnumerator AlgorithmThreadMethod()
        {
            //print("AlgorithThreadMethod()");
            //try
            //{
            _prevUpdateGeneration = 0;
            _prevUpdateTimeTick   = DateTime.Now.Ticks;

            for ( ; ;)
            {
                // This has been moved to inside the NeatEvolutionAlgorithm.
                // Otherwise there were problems and inconsistencies when
                // interactive evolution was aborted, or during the first
                // generation (because it starts by entering this loop, while the
                // others start at some event). It is a bit confusing, but now
                // everything seems in order.
                //_currentGeneration++;

                yield return(Coroutiner.StartCoroutine(PerformOneGeneration()));

                //  print("Performed one generation");

                // UpdateTest() returns true if it is time for an update event
                if (UpdateTest())
                {
                    _prevUpdateGeneration = _currentGeneration;
                    _prevUpdateTimeTick   = DateTime.Now.Ticks;
                    OnUpdateEvent();
                }

                // Check if a pause has been requested.
                // Access to the flag is not thread synchronized, but it doesn't really matter if
                // we miss it being set and perform one other generation before pausing.
                if (_pauseRequestFlag || _genomeListEvaluator.StopConditionSatisfied)
                {
                    // Signal to any waiting thread that we are pausing
                    // _awaitPauseEvent.Set();

                    // Reset the flag. Update RunState and notify any listeners
                    // of the state change.
                    //   _pauseRequestFlag = false;
                    //   _runState = RunState.Paused;
                    OnUpdateEvent();
                    OnPausedEvent();
                    break;
                    // Wait indefinitely for a signal to wake up and continue.
                    // _awaitRestartEvent.WaitOne();
                }
            }
            //}
            //catch(ThreadAbortException)
            //{   // Quietly exit thread.
            //}
        }
예제 #28
0
        internal static void MakeDownloadCall(string url, Action <string> resultCallback)
        {
            EdExLogger.LoggerInstance.LogWithTimeStamp("Downloading file: " + url);
            var www = UnityWebRequest.Get(url);

            AppCenterEditor.RaiseStateUpdate(AppCenterEditor.EdExStates.OnHttpReq, url, AppCenterEditorHelper.MSG_SPIN_BLOCK);
            Coroutiner.StartCoroutine(PostDownload(www, response =>
            {
                resultCallback(WriteResultFile(url, response));
            }, AppCenterEditorHelper.SharedErrorCallback));
        }
예제 #29
0
        private IEnumerator CheckTouch()
        {
            yield return(new WaitForSeconds(1));

            if ((Time.time - matchTileGridModel.lastTouchedTimestamp) >= matchTileGridModel.secondsUntilHint)
            {
                matchTileGridModel.lastTouchedTimestamp = Time.time;
                DisplayHint();
            }

            Coroutiner.StartCoroutine(CheckTouch());
        }
예제 #30
0
 public void Awake()
 {
     if (instance != null)
     {
         Destroy(gameObject);
     }
     else
     {
         instance = this;
     }
     DontDestroyOnLoad(gameObject);
 }