Created
September 29, 2016 03:06
-
-
Save dskjal/5a8f32f6135f2142c7db6581586baf38 to your computer and use it in GitHub Desktop.
Unity でヒープにごみを出さない WaitForSeconds
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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