Search Unity

My Scene Loading Script Only Works When I Play Test In The Editor.

Discussion in 'Editor & General Support' started by Zorro-Games, Jul 5, 2021.

  1. Zorro-Games

    Zorro-Games

    Joined:
    Jul 17, 2016
    Posts:
    5
    Hello,
    For some reason, my script works when I play test in the editor but when I create a build, the do not destroy on load function is no longer work when I create an executable build.

    Thanks for the help!

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.SceneManagement;
    5.  
    6. public class LoadNextLevel : MonoBehaviour {
    7.  
    8.     private GameObject Player;
    9.     private GameObject Camera;
    10.  
    11.     void OnTriggerEnter2D(Collider2D other)
    12.     {
    13.         GameObject Player = GameObject.FindGameObjectWithTag("Player");
    14.         GameObject Camera = GameObject.FindGameObjectWithTag("MainCamera");
    15.      
    16.         if (other.CompareTag("Player"))
    17.         {
    18.             SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
    19.             DontDestroyOnLoad(Player);
    20.             DontDestroyOnLoad(Camera);
    21.         }
    22.     }
    23. }
     
  2. diXime

    diXime

    Joined:
    Oct 2, 2018
    Posts:
    162
    Hello,
    I am not familiar with that particular method, but to my understanding, the destroying of objects happens during the loading of the new scene. So maybe put "DontDestroyOnLoad" in Awake in the new scene.

    Hope it helps,
     
  3. Zorro-Games

    Zorro-Games

    Joined:
    Jul 17, 2016
    Posts:
    5
    I will probably have to try that, thanks :)
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    20,155
    I'm not sure where you came up with the above quirky combination of finding Player and Camera by tag (??!) and then destroying those same things concurrent with a scene load... that seems extremely unlikely to have ever been reasonably engineered.

    In fact, I can't even imagine why you would ever need any of those things to know about each other.

    Instead, start with some basic tutorials for what you're trying to do:

    - have a trigger area at the exit of the level
    - have an OnTrigger responder that loads to the next level when the player enters the trigger area.

    That should be IT, finito and done, nothing more.

    Cameras and Players are ABSOLUTELY NO BUSINESS of the level/scene linker.
     
unityunity