Search Unity

Using 'Invoke'

Discussion in 'Scripting' started by Gabe-Tucker, Nov 27, 2015.

  1. Gabe-Tucker

    Gabe-Tucker

    Joined:
    Nov 26, 2015
    Posts:
    94
    In my Asteroids game, when the ship collides with the asteroid, it explodes and dies, but it doesn't reload the scene. Please help.
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class ShipControls : MonoBehaviour
    5. {
    6.     public ParticleSystem explodeFx;
    7.  
    8.     void OnCollisionEnter2D (Collision2D collision)
    9.     {
    10.         if (collision.gameObject.tag == "Asteroid Tag")
    11.         {
    12.             Invoke ("reload", 2.0f);
    13.             ParticleSystem fx = Instantiate (explodeFx, transform.position, Quaternion.identity) as ParticleSystem;
    14.             Destroy (fx.gameObject, fx.duration + fx.startLifetime);
    15.             Destroy (gameObject);
    16.         }
    17.     }
    18.  
    19.     void reload()
    20.     {
    21.         Application.LoadLevel(Application.loadedLevel);
    22.     }
    23. }
     
  2. Dantus

    Dantus

    Joined:
    Oct 21, 2009
    Posts:
    5,667
    Invoke stays alive within this particular MonoBehaviour instance, just like e.g. coroutines.
    You are destroying the game object and with the game object, you are destroying this MonoBehaviour instance in which you started the invoke. As invoke is part of the MonoBehaviour instance, you are destroying the invoke call as well.

    You have to make sure that invoke is called in a MonoBehaviour instance that is not being destroyed.
     
  3. Gabe-Tucker

    Gabe-Tucker

    Joined:
    Nov 26, 2015
    Posts:
    94
    Thank you, Dantus. It worked.