如何从已被破坏的外部GameObject执行协程

时间:2018-10-19 15:25:21

标签: c# unity3d coroutine

我想从另一个脚本启动协程。协程位于PlayerControl脚本的内部,而EnemyControl脚本保留触发协程的行。问题是协程无法执行,因为持有EnemyControl脚本的游戏对象被破坏了。

现在我的问题是:即使游戏物体被摧毁,如何启动协程?我之所以这么问,是因为听说协程会在游戏物体销毁后停止工作。

调用协程的EnemyControl脚本:

int achieveResult2 = PlayerPrefsManager.GetAchievement("achieveFirstKill_Key");

        if (achieveResult2 == 0) {
            PlayerPrefsManager.SetAchievement ("achieveFirstKill_Key", 1);

            playerShip.GetComponent<PlayerControl>().achievements.Add("First Kill");
            playerShip.GetComponent<PlayerControl>().achieveCntr = playerShip.GetComponent<PlayerControl>().achievements.Count;

            StartCoroutine(ShowAchievements());
        }

PlayerControl脚本内部的协程:

public IEnumerator ShowAchievements () {
    yield return new WaitForSeconds(0.5f);

    for (int i = 0; i < achieveCntr; i++) {

        achievementText.GetComponent<AchievementTxt> ().ShowAchieveText (achievements [i]);
        achievementText.GetComponent<AchievementTxt> ().achieveTxtTimerRunning = true;

        achievements.Remove(achievements [i]);

        yield return new WaitForSeconds(2f);
    }
}

1 个答案:

答案 0 :(得分:2)

只需将您调用的方法添加到播放器中即可在本地启动Coroutine。

比起安全地消灭敌人对象,因为它不再负责启动协程:

PlayerControl

public void ShowAchievements()
{
    StartCoroutine (ShowAchievementsRoutine ());
}

private IEnumerator ShowAchievementsRoutine () 
{
    yield return new WaitForSeconds(0.5f);

    for (int i = 0; i < achieveCntr; i++) 
    {

        achievementText.GetComponent<AchievementTxt> ().ShowAchieveText (achievements [i]);
        achievementText.GetComponent<AchievementTxt> ().achieveTxtTimerRunning = true;

        achievements.Remove(achievements [i]);

        yield return new WaitForSeconds(2f);
    }
}

并从敌人的普通方法中调用它:

 playerShip.GetComponent<PlayerControl>().ShowAchievements();