2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Unity]シリアライズできるWaitForSeconds

Posted at

GCをなるべく抑えるためにWaitForSecondをキャッシュして、さらに待ち時間をエディットできるようにしようと思うと
下記のコードのように変数と初期化処理が無駄に増えて面倒です

キャッシュ.cs

        [SerializeField]
        private float waitSecond;

        private WaitForSeconds wait;

        private void Awake()
        {
            wait = new WaitForSeconds(WaitSecond);
        }

        IEnumerator Coroutine()
        {
            while (true)
            {
                yield return wait;
            }
        }

シリアライズできるWaitForSecondがあればすべて解決というわけで作りました

SerializableWaitForSeconds.cs

    [Serializable]
    public class SerializableWaitForSecond : CustomYieldInstruction
    {
        public SerializableWaitForSecond(float second)
        {
            wait_Sec = second;
        }

        [SerializeField]
        private float wait_Sec;

        private float deltaTime;

        private bool isFirstMoveNext = true;
        public override bool keepWaiting
        {
            get
            {

                deltaTime += isFirstMoveNext ? 0 : Time.deltaTime;
                var waiting = wait_Sec >= deltaTime;
                isFirstMoveNext = false;
                if (!waiting)
                {
                    deltaTime = 0;
                    isFirstMoveNext = true;
                }
                return waiting;
            }
        }
    }

使う側のコードはこんな感じ

使い方
        [SerializeField]
        private SerializableWaitForSecond Wait;

        IEnumerator Coroutine()
        {
            while (true)
            {
                yield return Wait;
            }
        }

keepWaitngにUnityからアクセスされたタイミングでDeltaTimeを加算すると
そのフレームのDeltaTime分ずれるので最初だけスキップしています
whileループ時に使えるように自動でリセットがかかるようにしているので
概ね標準のWaitForSecondと変わらない感じで使えると思います

GCも極力抑えられるはずです

2
0
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?