コルーチン関数が呼び出されるたびに、timeLeft
変数が変更されています。最初に実行中のコルーチン関数を再度呼び出すと、複数のコルーチン関数がtimeLeft
変数を同時に変更して、現在の問題になります。
ブール変数を使用してコルーチンが既に実行されていることを検出し、開始が再び行われる場合がありますが、同時に複数のタイマーを作成することに言及しました。各関数呼び出しは、それのためtimeLeft
変数を持つようにCountdown
関数内timeLeft
変数.Move
:2つのオプションがあります。また、異なるText
コンポーネントを使用して各関数呼び出しのText
を変更するように、countText
変数にも同じ操作を行います。全体コルーチン機能.Move
public IEnumerator Countdown()
{
float timeLeft = 5f;
Text countText = GameObject.Find("TextForThisCounter").GetComponent<Text>();
while (timeLeft > 0)
{
yield return new WaitForSeconds(1.0f);
countText.text = timeLeft.ToString("f0");
timeLeft--;
}
}
別のクラスにタイマーとするとき、タイマーが行われている中にダニがあるあなたに、各第二に通知するコールバックAction
を使用しています。より移植性と再利用性が高いので、この方法をお勧めします。 IDを実装して、実行が終了したタイマーを特定することもできます。
タイマーは、別のスクリプトに移動:
public struct CountDownTimer
{
private static int sTimerID = 0;
private MonoBehaviour monoBehaviour;
public int timer { get { return localTimer; } }
private int localTimer;
public int timerID { get { return localID; } }
private int localID;
public CountDownTimer(MonoBehaviour monoBehaviour)
{
this.monoBehaviour = monoBehaviour;
localTimer = 0;
//Assign timer ID
sTimerID++;
localID = sTimerID;
}
public void Start(int interval, Action<int> tickCallBack, Action<int> finshedCallBack)
{
localTimer = interval;
monoBehaviour.StartCoroutine(beginCountDown(tickCallBack, finshedCallBack));
}
private IEnumerator beginCountDown(Action<int> tickCallBack, Action<int> finshedCallBack)
{
while (localTimer > 0)
{
yield return new WaitForSeconds(1.0f);
localTimer--;
//Notify tickCallBack in each clock tick
tickCallBack(localTimer);
}
//Notify finshedCallBack after timer is done
finshedCallBack(localID);
}
}
用途:
スタートタイマー4倍異なるIDを持つ各。
void Start()
{
createAndStartNewTimer();
createAndStartNewTimer();
createAndStartNewTimer();
createAndStartNewTimer();
}
public void createAndStartNewTimer()
{
//Create new Timer
CountDownTimer timer = new CountDownTimer(this);
//What to do each second time tick in the timer
Action<int> tickCallBack = (timeLeft) =>
{
Debug.Log(timeLeft.ToString("f0"));
};
//What to do each second time tick in the timer
Action<int> finshedCallBack = (timeriD) =>
{
Debug.Log("Count Down Timer Done! ID: " + timeriD);
};
//Start Countdown Timer from 5
timer.Start(5, tickCallBack, finshedCallBack);
}
このように、コルーチンは同時に2回実行されますか? – lockstock
はい、そうです。したがって、On Click()リストに1つ以上のタスク(合計3つのタスク)を追加すると、3回実行されます。なぜそれはこのように振る舞うのですか? – Gusto