LoginSignup
1
3

More than 5 years have passed since last update.

UniRx のみで Cube を動かす

Last updated at Posted at 2016-12-23

UniRx のみで一定時間かけて Cube を動かすサンプルです。

以下のサンプルでは、1.2 秒かけて Cube を (0, 0, 0) から (0, 3, 0) まで移動させています。

    public void Move(GameObject gameObject)
    {
        Observable.Create<Unit>(observer =>
        {
            float elapsed = 0;
            float duration = 1.2f;
            var disposable = Observable.Interval(TimeSpan.FromMilliseconds(11f)).Subscribe(e =>
            {
                elapsed += Time.deltaTime;
                float y = Mathf.Lerp(0, 3, elapsed / duration);
                gameObject.transform.position = new Vector3(0, y, 0);
                if (elapsed > duration)
                {
                    observer.OnCompleted();
                }
            });
            return Disposable.Create(() => disposable.Dispose());
        }).Subscribe();
    }

OnCompleted() をコールしているので、リークはしていない(はず)。

Observable.FromCoroutine を使う

    public void Move2(GameObject gameObject)
    {
        var disposable = Observable.FromCoroutine(() => MoveInternal(gameObject)).Subscribe();
        // disposable.Dispose() でキャンセル
    }

    private IEnumerator MoveInternal(GameObject gameObject)
    {
        float elapsed = 0;
        float duration = 1.2f;
        while (elapsed < duration)
        {
            elapsed += Time.deltaTime;
            float y = Mathf.Lerp(0, 3, elapsed / duration);
            gameObject.transform.position = new Vector3(0, y, 0);
            yield return null;
        }
    }
1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3