HI, i just have to reload the level when the player is died before that the scene has to wait for 2 seconds, no errors in the script but i don’t know why it is not reloading the scene. Any help please, Thanks.
public BodyPart bodyparts;
public int totalParts = 5;
void OnCollisionEnter2D(Collision2D target)
{
if(target.gameObject.tag == "Deadly")
{
OnExploads();
}
}
public void OnExploads()
{
StartCoroutine("Die");
Destroy (gameObject);
var t = transform;
for (int i = 0; i < totalParts; i++) {
t.TransformPoint (0, -100, 0);
BodyPart clone = Instantiate(bodyparts, t.position, Quaternion.identity) as BodyPart;
clone.GetComponent<Rigidbody2D>().AddForce(Vector3.right * Random.Range(-50, 50));
clone.GetComponent<Rigidbody2D>().AddForce(Vector3.up * Random.Range(100, 400));
}
}
IEnumerator Die()
{
yield return new WaitForSeconds(2);
Application.LoadLevel (Application.loadedLevel);
}
}
Propably after starting coroutine “Destroy” function “cancels” coroutine especially when you set delay like WaitForSeconds. Try to remove “Destroy” function just after starting coroutine and test it.
public void OnExploads()
{
StartCoroutine(“Die”);
Destroy (gameObject);
// More code
}
You start the coroutine and then destroy the coroutine. A coroutine is bound to the object that called it so when you destroy the object, you also terminate the coroutine. You would be better with a callback. A tad bit more complex but so much better.
Or move the destroy to the coroutine.
IEnumerator Die()
{
yield return new WaitForSeconds(2);
Application.LoadLevel (Application.loadedLevel);
Destroy(gameObject);
}
If you wonder why you get the bodyparts, this is because Destroy is delayed to the end of the frame so whatever comes next in the method is also called.
Now for the callback:
IEnumerator Die(System.Action onCompletion)
{
yield return new WaitForSeconds(2);
onCompletion();
}
void Callback(){
Application.LoadLevel (Application.loadedLevel); // This should be changed to use SceneManager
Destroy(gameObject);
}
public void OnExploads()
{
StartCoroutine(Die(Callback));
this.GetComponent<Collider>().enabled = false;
this.GetComponent<Renderer>().enabled = false;
var t = transform;
for (int i = 0; i < totalParts; i++) {
t.TransformPoint (0, -100, 0);
BodyPart clone = Instantiate(bodyparts, t.position, Quaternion.identity) as BodyPart;
clone.GetComponent<Rigidbody2D>().AddForce(Vector3.right * Random.Range(-50, 50));
clone.GetComponent<Rigidbody2D>().AddForce(Vector3.up * Random.Range(100, 400));
}
}
Since you are delaying the destruction you need to disable the rendering and the collision.