0
\$\begingroup\$

How do I check if an object has been destroyed. And do something like change scenes 2 seconds later.

this is what I tried:

float delay = 2

void OnDestroy(){

 delay-= Time.deltaTime;
 if(delay<=0){
   Application.LoadLevel("scene2");
  }
}
\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

you can use another script(for example GameManager) because when gameObject Destroyed haven't script component for checking if Delay <= 0

using UnityEngine;
using System.Collections;

public class MyObject: MonoBehaviour {

void Start(){
    Destroy (gameObject);

}

void OnDestroy(){
    GameManager.Instance.StartCoroutine ("Delay");

    }
 }

using UnityEngine;
using System.Collections;

public class GameManager : MonoBehaviour {
    public static GameManager Instance;


    void Awake () {
        Instance = this;
    }

    IEnumerator Delay(){
        yield return new WaitForSeconds (2);
        print ("that works");
        Application.LoadLevel ("scene2");
    }
}

or you can use Invoke for delay

using UnityEngine;
using System.Collections;

public class MyObject : MonoBehaviour {

    void Start(){
        Destroy (gameObject);
    }

    void OnDestroy(){
        GameManager.Instance.Invoke ("Delay", 2);

    }
}

using UnityEngine;
using System.Collections;

public class GameManager : MonoBehaviour {
    public static GameManager Instance;

    void Awake () {
        Instance = this;
    }

    void Delay(){
        print ("that works");
        Application.LoadLevel ("scene2");
    }
}
\$\endgroup\$
2
  • 1
    \$\begingroup\$ If you make the GameManager a static class, you don't even need need to do the whole GetComponent thing, you can just say "GameManager.NextLevel()". It's only slightly quicker in terms of actual performance, but I think making a GameManager class static is just good practice. \$\endgroup\$ Commented Aug 3, 2016 at 9:39
  • \$\begingroup\$ Then I replace print("That works!") with Application.LoadLevel("scene2")? \$\endgroup\$
    – kp21
    Commented Aug 3, 2016 at 10:34

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .