I think your problem is that you are destroying the object that is running the coroutine.
void OnTriggerEnter(Collider other)
{
if (other.tag == "Boundary")
{
return;
}
if (other.tag == "Player")
{
Instantiate(playerExplosion, other.transform.position, other.transform.rotation);
StartCoroutine(WaitMe());
//score store in PlayerPrefs
}
Destroy(other.gameObject);
Instantiate(explosion, transform.position, transform.rotation);
// Remove the visual object
renderer.enabled = false;
}
IEnumerator WaitMe()
{
PlayerPrefs.SetInt ("score", GameObject.FindWithTag ("GameController").GetComponent <GameController> ().score);
yield return new WaitForSeconds (3f);
// Destroy the object later on
Application.LoadLevel(nextlevel);
Destroy(gameObject);
}
Yes this was the error in the script. I somehow managed to tranfer the coroutine in the gamecontroler object and now it works as I wanted! Thanks a lot!
I presume you want to wait before doing the “Destroy Object Stuff” if the tag is the player. Easiest way here is to make OnTriggerEnter a coroutine itself - otherwise what you are doing is starting a coroutine - but the rest of your code carries on as soon as it yields (not after the time delay is finished)
public class DestroyByContact : MonoBehaviour {
public GameObject explosion;
public GameObject playerExplosion;
// int score;
IEnumerator OnTriggerEnter(Collider other)
{
if (other.tag == "Boundary")
{
yield break;
}
if (other.tag == "Player")
{
Instantiate(playerExplosion, other.transform.position, other.transform.rotation);
//score store in PlayerPrefs
PlayerPrefs.SetInt ("score", GameObject.FindWithTag ("GameController").GetComponent <GameController> ().score);
yield return new WaitForSeconds(3);
}
Destroy(other.gameObject);
Destroy(gameObject);
Instantiate(explosion, transform.position, transform.rotation);
}
}
can you explain what exactly you are trying to do?
– flamyInstead of using Coroutines I would recommend to use timers and Update function.
– GenuiTix@GenuiTix I disagree with that.
– whydoidoit