예제 #1
0
    // Use this for initialization
    void Start()
    {
        // Change HP text when value is changed
        hp.SubscribeToText(hpText);

        // Add animation ( we use LeanTween for this because it's a simple library that just works )
        hp.Subscribe(_ => AnimateObj(hpText.gameObject));

        // HP Bar
        hp.Subscribe(currentHP => {
            float normalizedHP = (currentHP / 100f);
            LeanTween.scaleX(hpBar, normalizedHP, 0.2f)
            .setEase(LeanTweenType.easeOutCirc);
        });

        // HP Delta
        hp.Throttle(TimeSpan.FromMilliseconds(500)).Subscribe(delayedHP => {
            float normalizedHP = (delayedHP / 100f);
            LeanTween.scaleX(hpDelta, normalizedHP, 0.2f)
            .setEase(LeanTweenType.easeInQuad);
        });

        // Button actions ------------------------
        damageButton.onClick.AddListener(DamageHP);
        resetButton.onClick.AddListener(ResetHP);
    }
        void Start()
        {
            // UnityEvent as Observable
            // (shortcut, MyButton.OnClickAsObservable())
            MyButton.onClick.AsObservable().Subscribe(_ => enemy.CurrentHp.Value -= 99);

            // Toggle, Input etc as Observable(OnValueChangedAsObservable is helper for provide isOn value on subscribe)
            // SubscribeToInteractable is UniRx.UI Extension Method, same as .interactable = x)
            MyToggle.OnValueChangedAsObservable().SubscribeToInteractable(MyButton);

            // input shows delay after 1 second
#if !(UNITY_4_6 || UNITY_5_0 || UNITY_5_1 || UNITY_5_2)
            MyInput.OnValueChangedAsObservable()
#else
            MyInput.OnValueChangeAsObservable()
#endif
            .Where(x => x != null)
            .Delay(TimeSpan.FromSeconds(1))
            .SubscribeToText(MyText);     // SubscribeToText is UniRx.UI Extension Method

            // converting for human visibility
            MySlider.OnValueChangedAsObservable()
            .SubscribeToText(MyText, x => Math.Round(x, 2).ToString());

            // from RxProp, CurrentHp changing(Button Click) is observable
            enemy.CurrentHp.SubscribeToText(MyText);
            enemy.IsDead.Where(isDead => isDead == true)
            .Subscribe(_ =>
            {
                MyToggle.interactable = MyButton.interactable = false;
            });

            // initial text:)
            IntRxProp.SubscribeToText(MyText);
        }
예제 #3
0
    // Use this for initialization
    void Start()
    {
        // spawn cubes at regular time interval
        //var spawnStream = Observable.Interval(TimeSpan.FromMilliseconds(500));

        // spawn cubes at random time interval
        var spawnStream = gameObject.AddComponent <ObservableRandomEventTrigger>();

        spawnStream.OnRandomEventAsObservable().Subscribe(_ => {
            var newCube = GameObject.CreatePrimitive(PrimitiveType.Cube);
            newCube.AddComponent <Rigidbody>();

            // when using prefabs, use instantiate
            //newCube = Instantiate(prefab, new Vector3(0, 0, 0), Quaternion.identity);

            // destroy cube, after reaching y = -5
            newCube.transform.ObserveEveryValueChanged(x => x.position).Subscribe(pos => {
                if (pos.y < -5f)
                {
                    Destroy(newCube);
                }
            });

            Debug.Log("SPAWNED NEW CUBE");
        });

        // get button and increment score
        tapScore.OnClickAsObservable().Subscribe(_ => {
            score.Value++;
        });

        // change score text according to text
        score.SubscribeToText(scoreText);
    }
예제 #4
0
    void Start()
    {
        gameOverText.text = string.Empty;
        restartText.text  = string.Empty;
        // 绑定分数、游戏结束、重新开始的text
        score.SubscribeToText(scoreText, s => $"得分: {score}");
        gameOver.Where(x => x).SubscribeToText(gameOverText, _ => "游戏结束");
        restart.Where(x => x).SubscribeToText(restartText, _ => "按R键重新开始");

        // 生成小行星
        var spawnStream = Observable
                          .Interval(TimeSpan.FromSeconds(spawnWait))
                          .Where(_ => !gameOver.Value)
                          .Do(_ =>
        {
            spawnPosition.x = Random.Range(-spawnValues.x, spawnValues.x);
            spawnPosition.z = spawnValues.z;
            spawnRotation   = Quaternion.identity;
            Instantiate(hazards[Random.Range(0, hazards.Length)], spawnPosition, spawnRotation);
        })
                          .Take(hazardCount)
                          .Delay(TimeSpan.FromSeconds(waveWait))
                          .RepeatSafe();

        spawnStream.Subscribe().AddTo(this);

        // 重新开始游戏
        var restartStream = Observable.EveryUpdate()
                            .Where(_ => Input.GetKeyDown(KeyCode.R))
                            .Where(_ => restart.Value);

        restartStream.Subscribe(_ => SceneManager.LoadScene(0));
    }
예제 #5
0
    // Use this for initialization
    void Start()
    {
        // also possible as singleton or other global gameobject
        _cubePool = new ColorCubePool(colorCubePrefab);

        // spawn cubes at random time interval with object pool
        var spawnStream = gameObject.AddComponent <ObservableRandomEventTrigger>();

        spawnStream.OnRandomEventAsObservable().Subscribe(_ => {
            var colorCube           = _cubePool.Rent();
            colorCube.ColorCubePool = _cubePool;

            Debug.Log("SPAWNED NEW CUBE FROM POOL");
        });

        // get button and increment score
        tapScore.OnClickAsObservable().Subscribe(_ => {
            score.Value++;
        });

        // change score text according to text
        score.SubscribeToText(scoreText);

        // destroy cubes
        destroyBoderCube.GetComponent <ObservableTriggerTrigger>().OnTriggerEnterAsObservable().Subscribe(x => {
            _cubePool.Return(x.GetComponent <ColorCube>());
            Debug.Log("DESTROYED " + x.gameObject.name);
        });
    }
예제 #6
0
    async void Start()
    {
        countButton
        .OnClickAsObservable()
        .Subscribe(_ => { Debug.Log("click"); });

        var count = new IntReactiveProperty(0);

        countButton
        .OnClickAsObservable()
        .Subscribe(_ => count.Value++);

        count.SubscribeToText(countText);

        checkToggle
        .OnValueChangedAsObservable()
        .Subscribe(b => checkText.gameObject.SetActive(b));

        slider
        .OnValueChangedAsObservable()
        .SubscribeToText(sliderValueText);

        dropdown.options.Add(new Dropdown.OptionData("hoge"));
        dropdown.OnValueChangedAsObservable()
        .Select(index => dropdown.options[index].text)
        .SubscribeToText(dropdownText);
        input
        // .OnValueChangedAsObservable()
        .OnEndEditAsObservable()
        .SubscribeToText(inputText);

        if (TouchScreenKeyboard.isSupported)
        {
            keyboradButton.OnClickAsObservable().Subscribe(async _ =>
            {
                if (kb != null)
                {
                    Debug.Log("already open");
                    return;
                }
                kb = TouchScreenKeyboard.Open("", TouchScreenKeyboardType.Default, false, false, false, false, "message...");
                Debug.Log($"after open. kb={kb}, status={kb.status}, {kb.text}");
                await UniTask.WaitUntil(() => kb != null && kb.status != TouchScreenKeyboard.Status.Visible);
                Debug.Log($"after input. kb={kb}, status={kb.status}, {kb.text}, {kb.wasCanceled}");
                if (kb.status == TouchScreenKeyboard.Status.Done)
                {
                    inputText.text = kb.text;
                }

                kb = null;
            });
        }
        else
        {
            Debug.Log("TouchScreenKeyboard not supported");
        }
    }
예제 #7
0
    // Use this for initialization
    void Start()
    {
        // ----------------------------------
        // Activate mainMenu
        // ----------------------------------
        mainMenu.SetActive(true);
        endMenu.SetActive(false);
        gameMenu.SetActive(false);


        // ----------------------------------
        // Setup scoreDelayed + scoreDelta
        // ----------------------------------

        // Score Delayed
        scoreDelayed = score.Throttle(TimeSpan.FromSeconds(1)).ToReactiveProperty();

        // Score Delta ( no need to have it as a private value since we're not gonna need to use it again in another function )
        var scoreDelta = score.Select(x => x - scoreDelayed.Value);

        // Change deltaScoreText and format it so that if the number is positive it has a "+" in front of it
        scoreDelta.SubscribeToText(deltaScoreText, x => (x > 0 ? ("+" + x) : x.ToString()));

        // Add animation everytime score delta changes
        scoreDelta.Subscribe(_ => AnimateObj(deltaScoreText.gameObject));

        scoreDelayed.Subscribe(delayedScore => {
            // Change text
            scoreText.text = delayedScore.ToString(); // You can also set it using scoreDelayed.SubscribeToText(scoreText);

            // Start animation
            AnimateObj(scoreText.gameObject);

            // Clear deltaScore ocne we've updated the score
            deltaScoreText.text = "";
        });

        // ----------------------------------
        // Setup highscore ( and save values )
        // ----------------------------------
        int lastHighScore = PlayerPrefs.GetInt("highscore");

        highscore = score.StartWith(lastHighScore).DistinctUntilChanged().Scan(int.MinValue, Math.Max).Do(x => PlayerPrefs.SetInt("highscore", x)).ToReactiveProperty();

        // ----------------------------------
        // Setup levels
        // ----------------------------------
        level.SubscribeToText(levelText, x => "Level " + x.ToString());

        // ----------------------------------
        // Button actions
        // ----------------------------------
        startButton.onClick.AddListener(StartGame);
        restartButton.onClick.AddListener(StartGame);
    }
    // Use this for initialization
    void Start( )
    {
        score.SubscribeToText(scroeText);

        //Add Score Value By Space KeyDown.
        var KeyDownStream = this.UpdateAsObservable()
                            .Where(_ => Input.GetKeyDown(KeyCode.Space))
                            .Subscribe(_ => {
            score.Value++;
        });
    }
예제 #9
0
    // Use this for initialization
    void Start( )
    {
        score.SubscribeToText(scroeText);
        var updateScore = this.UpdateAsObservable().Subscribe(_ => { score.Value++; });

        //Stop By Space Key Down.
        var KeyDownStream = this.UpdateAsObservable()
                            .Where(_ => Input.GetKeyDown(KeyCode.Space))
                            .Subscribe(_ => {
            //Disable Observer
            updateScore.Dispose();
        });
    }
예제 #10
0
    private void Start()
    {
        _cubePool = new ColorCubePool(colorCubePrefab);

        ObservableRandomEventTrigger spawnStream = gameObject.AddComponent <ObservableRandomEventTrigger>();

        spawnStream.OnRandomEventAsObservable().Subscribe(_ => {
            var colorCube           = _cubePool.Rent();
            colorCube.ColorCubePool = _cubePool;

            // Debug.Log("SPAWNED NEW CUBE FROM POOL");
        });

        ObservableTriggerTrigger scoreCubeCountTrigger = scoreCube.AddComponent <ObservableTriggerTrigger>();

        scoreCubeCountTrigger.OnTriggerEnterAsObservable().Subscribe(x => {
            if (x.GetComponent <Renderer>().material.color.r == scoreCube.GetComponent <Renderer>().material.color.r)
            {
                isScoreable.Value = true;
            }
        });
        scoreCubeCountTrigger.OnTriggerExitAsObservable().Subscribe(_ => {
            isScoreable.Value = false;
        });

        ObservableRandomEventTrigger scorCubeRandomColorTrigger = scoreCube.AddComponent <ObservableRandomEventTrigger>();

        scorCubeRandomColorTrigger.OnRandomEventAsObservable().Subscribe(_ => {
            scoreCube.GetComponent <Renderer>().material = _materialsAlpha[UnityEngine.Random.Range(0, 2)];
        });

        scoreButton.OnClickAsObservable().Subscribe(_ => {
            if (isScoreable.Value)
            {
                score.Value++;
                isScoreable.Value = false;
            }
            else
            {
                score.Value--;
            }
        });

        score.SubscribeToText(scoreText);
    }
예제 #11
0
    // Use this for initialization
    void Start()
    {
        // also possible as singleton or other global gameobject
        _cubePool = new ColorCubePool(colorCubePrefab);

        // spawn cubes at random time interval with object pool
        var spawnStream = gameObject.AddComponent<ObservableRandomEventTrigger>();
        spawnStream.OnRandomEventAsObservable().Subscribe(_ => {
            var colorCube = _cubePool.Rent();
            colorCube.ColorCubePool = _cubePool;

            Debug.Log("SPAWNED NEW CUBE FROM POOL");
        });

        // check for scorecount
        scoreCube.AddComponent<ObservableTriggerTrigger>();
        scoreCube.GetComponent<ObservableTriggerTrigger>().OnTriggerEnterAsObservable().Subscribe(x => {
            if (x.GetComponent<Renderer>().material.color.r == scoreCube.GetComponent<Renderer>().material.color.r) {
                isScoreable.Value = true;
            }
        });
        // disable scorecount
        scoreCube.GetComponent<ObservableTriggerTrigger>().OnTriggerExitAsObservable().Subscribe(_ => {
            isScoreable.Value = false;
        });
        // change color for score border
        scoreCube.AddComponent<ObservableRandomEventTrigger>();
        scoreCube.GetComponent<ObservableRandomEventTrigger>().OnRandomEventAsObservable().Subscribe(_ => {
            scoreCube.GetComponent<Renderer>().material = _materialsAlpha[UnityEngine.Random.Range(0, 2)];
        });

        // get button and increment score
        scoreButton.OnClickAsObservable().Subscribe(_ => {
            if (isScoreable.Value) {
                score.Value++;
                isScoreable.Value = false;
            } else {
                score.Value--;
            }
        });

        // change score text according to text
        score.SubscribeToText(scoreText);
    }
    // Start is called before the first frame update
    void Start()
    {
        if (clearPlayerPrefs)
        {
            PlayerPrefs.DeleteAll();
        }

        if (!PlayerPrefs.HasKey("level"))
        {
            PlayerPrefs.SetInt("level", 0);
        }

        if (!PlayerPrefs.HasKey("score"))
        {
            PlayerPrefs.SetInt("score", 0);
        }

        score.SubscribeToText(scoreText);
        score.Value = PlayerPrefs.GetInt("score");
    }
예제 #13
0
    // Use this for initialization
    void Start()
    {
        // Change text when score is changed
        score.SubscribeToText(scoreText);

        // Add animation ( we use LeanTween for this because it's a simple library that just works )
        score.Subscribe(_ => LeanTween.scale(scoreText.gameObject, Vector3.one, 0.2f).setFrom(Vector3.one * 0.5f).setEase(LeanTweenType.easeOutBack));

        /*
         * // Two above lines can also be written as follows :
         * score.Subscribe(x => {
         *    scoreText.Text = x.toString();
         *    LeanTween.scale(scoreText.gameObject, Vector3.one, 0.2f).setFrom(Vector3.one*0.5f).setEase(LeanTweenType.easeOutBack)
         * });
         */

        // Button actions ------------------------
        addButton.onClick.AddListener(() => {
            score.Value++;
        });
    }
예제 #14
0
    // Use this for initialization
    void Start()
    {
        // Score from example 1 ( see example for more comments )
        score.SubscribeToText(scoreText);
        score.Subscribe(_ => AnimateObj(scoreText.gameObject));


        // Highscore ---------------------------

        // Scans through all values and gets the highest ( Math.Max( last, new ) ) and use it to compare with future values
        var highscore = score.Scan(int.MinValue, Mathf.Max).ToReactiveProperty();

        // Change text when highscore changes ( we format the string to BEST x before setting it to text )
        highscore.SubscribeToText(highscoreText, x => string.Format("BEST {0}", x));

        // Add animation when highscore changes
        highscore.Subscribe(_ => AnimateObj(highscoreText.gameObject));


        // Button actions ------------------------
        addButton.onClick.AddListener(() => score.Value++);
        resetButton.onClick.AddListener(() => score.Value = 0);
    }