This question was
closed Feb 11, 2017 at 12:23 AM by
LennyBench for the following reason:
The question is answered, right answer was accepted
Question by
LennyBench · Feb 10, 2017 at 06:03 AM ·
c#coroutine
Weird C# Coroutine problem
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class loveSpellBehavior : MonoBehaviour {
public GameObject lovestruck;
private List<TroopBehavior> troopsHit = new List<TroopBehavior>();
void OnTriggerEnter2D(Collider2D coll)
{
if (coll.gameObject.layer == 8 && coll.GetComponent<TroopBehavior> () && !troopsHit.Contains(coll.GetComponent<TroopBehavior>())) {
StartCoroutine(Stun(coll.GetComponent<TroopBehavior>()));
}
}
IEnumerator Stun (TroopBehavior tB)
{
troopsHit.Add (tB);
float speed = tB.speed;
tB.speed = 0;
tB.enabled = false;
tB.GetComponent<Animator> ().SetBool ("stop", true);
yield return new WaitForSeconds (0.1f);
tB.GetComponent<Animator> ().SetBool ("stop", false);
Destroy(Instantiate (lovestruck, tB.transform.position, Quaternion.identity, tB.transform), 2);
yield return new WaitForSeconds(2f);
print ("LALWALDWAL");
tB.enabled = true;
tB.speed = speed;
}
}
When I run this code and the function is called, it stops short at the WaitForSeconds(2f) and doesn't print the string. I've worked with Coroutines before and haven't encountered this before. Please help!
Comment
hi, out of curiosity - does it still get stuck if you comment out your Destroy(instantiate) row? I wonder if there is not a conflict there.
Is the game object that has the loveSpellBehavior on getting destroyed?
Coroutines are owned by the object that starts them, if that object gets destroyed the coroutine will be stopped.
Oh yup, that was it. Looks like I learned something new today. Thanks!