Skip to content

Instantly share code, notes, and snippets.

@dskjal
Created September 29, 2016 03:06
Show Gist options
  • Save dskjal/5a8f32f6135f2142c7db6581586baf38 to your computer and use it in GitHub Desktop.
Save dskjal/5a8f32f6135f2142c7db6581586baf38 to your computer and use it in GitHub Desktop.
Unity でヒープにごみを出さない WaitForSeconds
// BEGIN MIT LICENSE BLOCK //
//
// Copyright (c) 2016 dskjal
// This software is released under the MIT License.
// http://opensource.org/licenses/mit-license.php
//
// END MIT LICENSE BLOCK //
/* 使い方
[SerializeField]
float interval = 1;
void Start() {
StartCoroutine(coroutine());
}
IEnumerator coroutine() {
var wfs = new VariableWaitForSeconds(interval);
while (true) {
// 実行するコード
yield return wfs.ChangeInterval(interval);
}
}
*/
using UnityEngine;
using System.Collections;
public class VariableWaitForSeconds : CustomYieldInstruction {
private float elapsed;
public float Interval { get; set; }
public override bool keepWaiting
{
get
{
elapsed += Time.deltaTime;
var isKeepWaiting = Interval >= elapsed;
if (!isKeepWaiting) {
// elapsed -= Interval だと 10 秒間隔のあとに 1 秒間隔に変更されたときに対応できない
elapsed = 0;
}
return isKeepWaiting;
}
}
public VariableWaitForSeconds(float interval) {
elapsed = 0;
Interval = interval;
}
public IEnumerator ChangeInterval(float interval) {
Interval = interval;
return this;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment