Reputation: 811
I want to start a Coroutine from another script. The Coroutine is inside of the PlayerControl-script and the EnemyControl-script holds the line that fires off the Coroutine. The problem is the Coroutine doesn’t get executed because the gameobject holding the EnemyControl-script gets destroyed.
Now my question is: How do you start a Coroutine even when the gameobject gets destroyed? I just ask because I heard that Coroutines stop working when the gameobject gets destroyed.
The EnemyControl-script that invokes the Coroutine:
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());
}
The Coroutine inside of the PlayerControl-script:
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);
}
}
Upvotes: 0
Views: 117
Reputation: 90679
Just add a method you call to the player which starts the Coroutine locally.
Than you can destroy the enemy object safely since it is not responsible for starting the Coroutine anymore:
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);
}
}
And call it as a normal method from the Enemy:
playerShip.GetComponent<PlayerControl>().ShowAchievements();
Upvotes: 2