以下协程在按UI按钮运行时将正常运行,并显示“ 3 ... 2 ... 1 ... 0”,然后消失。但是,当作为事件处理程序委托HandleRewardBasedVideoClosed(AdMob的一部分)的一部分运行时,它将显示“ 3 ... 1 ...”,然后消失。对于我的一生,我无法弄清楚为什么当以这两种不同方式调用时,它的行为会有所不同。
public IEnumerator Countdown() {
timeLeft = 3;
while (timeLeft >= 0) {
countdownText.text = timeLeft.ToString();
yield return new WaitForSecondsRealtime(1.0f);
timeLeft--;
}
if (timeLeft < 0) {
countdownText.gameObject.SetActive (false);
}
}
public void HandleRewardBasedVideoClosed(object sender, EventArgs args){
MonoBehaviour.print("HandleRewardBasedVideoClosed event received");
if (reward) {
StartCoroutine ( gm.Countdown ());
} else
SceneManager.LoadScene (SceneManager.GetActiveScene ().name);
}
答案 0 :(得分:1)
我对此很怀疑。倒数计时实际上是在如此快地执行“ 3.2 .. 2.1 .. 0.SetActive(false)”,以至于您看不到它运行协程两次吗?如果是这样,以下代码将解决该特定问题(如果是这种情况):
private bool isCountingDown = false;
public IEnumerator Countdown()
{
if ( isCountingDown ) return;
isCountingDown = true;
for ( int timeLeft = 3; timeLeft >= 0; timeLeft-- )
{
countdownText.text = timeLeft.ToString();
yield return new WaitForSecondsRealtime(1.0f);
}
countdownText.gameObject.SetActive (false);
isCountingDown = false;
}
public void HandleRewardBasedVideoClosed(object sender, EventArgs args)
{
MonoBehaviour.print("HandleRewardBasedVideoClosed event received");
if (reward) {
// This might be a redundant check, as we're doing this in the
// Coroutine, but we may as well not go through the process of
// calling it in the first place.
if (! isCountingDown ) StartCoroutine ( gm.Countdown ());
} else
SceneManager.LoadScene (SceneManager.GetActiveScene ().name);
}