Search Unity

OnDestroy already queued

Discussion in 'Scripting' started by janlovsin, Aug 25, 2019.

  1. janlovsin

    janlovsin

    Joined:
    Jun 7, 2018
    Posts:
    12
    I'm reusing a few objects, so when I need them I SetParent and when changing scenes I SetParent back to old one so they don't get destroyed.

    Code (CSharp):
    1. // on ROOT object in scene -> calling leaderboard.BeOnDestroy() here, still calls all
    2. // contentAreaObject's OnDestroy()'s
    3. private void OnDestroy()
    4. {
    5.     Debug.Log("TEST DESTROY");
    6.     leaderboard.BeOnDestroy();
    7. }
    8.  
    9. // but calling leaderboard.BeOnDestroy() here works as expected (without calling OnDestroy
    10. // on contentAreaObject's)
    11. private void SceneChange()
    12. {
    13.     leaderboard.BeOnDestroy();
    14.     SceneSwitcher.LoadScene(GameSettings.INTRO_SCENE);
    15. }
    16.  
    17. // a method on a gameObject that is created in 1st scene and never get's destroyed
    18. public void BeOnDestroy()
    19. {
    20.     for (int i = 0; i < contentAreaObjects.Count; i++)
    21.     {
    22.         contentAreaObjects[i].transform.SetParent(gameObject.transform, false);
    23.     }
    24. }
    Is there any way I can SetParent in OnDestroy without objects still getting destroyed?
     
  2. No. Don't do that. If you want game objects to be preserved, call DontDestroyOnLoad on them.
     
  3. janlovsin

    janlovsin

    Joined:
    Jun 7, 2018
    Posts:
    12
    I create 1000 of those objects and bind them to DontDestroyOnLoad on 1st scene, but then I have to reuse them by reparent them to each leaderboard(scrollviews with 'content' <--), and before changing scene I have to reparent them again else they get destroyed because their parent get's destroyed. Which works fine if I manually reparent them before changing scene, but doing it in OnDestroy, even though it still manages to call BeOnDestroy, the objects still get destroyed by the scene.
     
  4. Organize them on a way that their parent don't get destroyed. There is no way to back off from the OnDestroy.
     
    Joe-Censored likes this.
  5. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    Redesign so you don't have child objects you wish to preserve attached to parents you are destroying.