Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by Foose · Aug 12, 2014 at 04:57 PM · c#scene-loadingapplication.loadlevel

Delete all GameObjects of last scene after Application.Loadlevel("New Scene")

hey. As the title says, I have the problem that whenever I switch to a new scene in Runtime, the GameObjects of the older scenes will not be deleted but stay in the hirachy. Is there any option to do that?

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

2 Replies

· Add your reply
  • Sort: 
avatar image
0

Answer by smallbit · Aug 12, 2014 at 05:02 PM

http://docs.unity3d.com/ScriptReference/Object.DontDestroyOnLoad.htmlput this command for each gameoject you want to keep in new scene, if you have many of them make one parent and put dontdestroyonload to this parent.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

Answer by Foose · Aug 12, 2014 at 05:12 PM

No, the problem is that I want to delete all but they stay :D I don't want to keep them. I will Post the Main Menu script of my first scene which I guess is the problem. Maybe you can see the failure.

 public class MainMenu : MonoBehaviour
 {
     //   Inspector tunable members   //
 
     public Texture ButtonTexture;
 
 
     
     public Vector2 CanvasSize;                  // size of window on canvas
 
     private Rect LoginButtonRect = new Rect((Screen.width / 2) - 100, (Screen.height / 2) - 21, 200, 43);                // Position of login button
     
                // position of resource indicators (not used yet)
 
     public Vector2 ButtonStartPos;              // position of first button in main menu
     public float ButtonScale;                   // size of main menu buttons
     public float ButtonYGap;                    // gap between buttons in main menu
     public float ChallengeDisplayTime;          // Number of seconds the request sent message is displayed for
     public Vector2 ButtonLogoOffset;            // Offset determining positioning of logo on buttons
     public float TournamentStep;                // Spacing between tournament entries
     public float MouseScrollStep = 40;          // Amount score table moves with each step of the mouse wheel
 
     public PaymentDialog paymentDialog;
 
     public GUISkin MenuSkin;           
 
     public int CoinBalance;
     public int NumLives;
     public int NumBombs;
 
     public Texture[] CelebTextures;
     public string [] CelebNames;
 
 
 
     //   Private members   //
 
 
     private static MainMenu instance;
 
     private static List<object>                 friends         = null;
     private static Dictionary<string, string>   profile         = null;
     private static List<object>                 scores          = null;
     private static Dictionary<string, Texture>  friendImages    = new Dictionary<string, Texture>();
     
     
     
     private Vector2 scrollPosition = Vector2.zero;
 
     
     
     private bool    haveUserPicture       = false;
     private float   tournamentLength      = 0;
     private int     tournamentWidth       = 512;
 
     private int     mainMenuLevel         = 0; // Level index of main menu
 
 
     private string popupMessage;
     private float popupTime;
     private float popupDuration;
 
     enum LoadingState 
     {
         WAITING_FOR_INIT,
         WAITING_FOR_INITIAL_PLAYER_DATA,
         DONE
     };
     
     private LoadingState loadingState = LoadingState.WAITING_FOR_INIT;
     
     void Awake()
     {
         Util.Log("Awake");
    
         paymentDialog = ((PaymentDialog)(GetComponent("PaymentDialog")));
 
 
             Debug.Log("CONFIGURE FACEBOOK CANVAS ");
             // INJECT TOP ADS
             
             string injectionAdsFacebook =
                 "var headerElement = document.createElement('div'); " +
                     "headerElement.id = ('adsWebFacebook')  ; " +
                     "headerElement.textContent = ('Check out our other great games: ...');" +
                     "headerElement.style.width = 400; " +
                     "headerElement.style.height = 200; " +
                     "headerElement.style.marginLeft = (window.innerWidth - 400)/2;" +
                     "headerElement.style.marginRight = (window.innerWidth - 400)/2;" +
                     "var body = document.getElementById('unityPlayerEmbed');" +
                     "var insertionPoint = body.children[0]; " +
                     "body.insertBefore(headerElement, insertionPoint);";
             
             Application.ExternalEval(injectionAdsFacebook);
             
             // Execute javascript in iframe to keep the player centered and recalculate resolution
             string javaScript = @"
                     window.onresize = function() {
                     var width = window.innerWidth;
                     var height = window.innerHeight;
  
                     var marginX = width * 0.1;
                     var marginY = height *0.1;
  
                      var appWidth = " + CanvasSize.x + @";
                       var appHeight = " + CanvasSize.y + @"; 
  
                     if(appWidth > window.innerWidth){
                         appWidth = (( window.innerWidth - marginX) / 800) * 800;
                         appHeight = (appWidth *10) /16; 
  
                     }
  
                     var unity = UnityObject2.instances[0].getUnity();
                     var unityDiv = document.getElementById(""unityPlayerEmbed"");
  
                     unity.style.width = appWidth + ""px"";
                     unity.style.height = appHeight + ""px"";
  
                     unityDiv.style.marginLeft = (width - appWidth)/2 + ""px"";
                     unityDiv.style.marginTop = (height - appHeight)/2 + ""px"";
                     unityDiv.style.marginRight = (width - appWidth)/2 + ""px"" ;
                     unityDiv.style.marginBottom = (height - appHeight)/2 + ""px"";
                 }
  
                 window.onresize(); // force it to resize now";
             Application.ExternalCall(javaScript);
             
             
             
         /*    string changeCanvasBackground = 
                 
                 "var body = document.getElementsByTagName('body');" +
                     "body[0].style.background-image =  \"url('https://tictacpuzzlesfb.parseapp.com/backgroundsFaceCanvas/spaceCanvasBack.png')\";" +
                     "body[0].background-size = 'cover'";
             
             Application.ExternalEval(changeCanvasBackground);  */
 
 
         // allow only one instance of the Main Menu
         if (instance != null && instance != this)
         {
             Destroy(gameObject);
             return;
         }
 
         DontDestroyOnLoad (gameObject);
         instance = this;
         
 
         // Initialize FB SDK
         enabled = false;
         FB.Init(SetInit, OnHideUnity);
     }
 
     private void SetInit()
     {
         Util.Log("SetInit");
         enabled = true; // "enabled" is a property inherited from MonoBehaviour
         if (FB.IsLoggedIn) 
         {
             Util.Log("Already logged in");
             OnLoggedIn();
             loadingState = LoadingState.WAITING_FOR_INITIAL_PLAYER_DATA;
         }
         else
         {
             loadingState = LoadingState.DONE;
         }
     }
 
     private void OnHideUnity(bool isGameShown)
     {
         Util.Log("OnHideUnity");
         if (!isGameShown)
         {
             // pause the game - we will need to hide
             Time.timeScale = 0;
         }
         else
         {
             // start the game back up - we're getting focus again
             Time.timeScale = 1;
         }
     }
     
     void LoginCallback(FBResult result)
     {
         Util.Log("LoginCallback");
         
         if (FB.IsLoggedIn)
         {
             OnLoggedIn();
         }
     }
     string meQueryString = "/v2.0/me?fields=id,first_name,friends.limit(100).fields(first_name,id,picture.width(128).height(128)),invitable_friends.limit(100).fields(first_name,id,picture.width(128).height(128))";
 
     void OnLoggedIn()
     {
         Util.Log("Logged in. ID: " + FB.UserId);
 
         // Reqest player info and profile picture
         FB.API(meQueryString, Facebook.HttpMethod.GET, APICallback);
         LoadPictureAPI(Util.GetPictureURL("me", 128, 128),MyPictureCallback);
 
         // Load high scores
         QueryScores();
     }
     
     private void QueryScores()
     {
         FB.API("/app/scores?fields=score,user.limit(20)", Facebook.HttpMethod.GET, ScoresCallback);
     }
     
     void APICallback(FBResult result)
     {
         Util.Log("APICallback");
         if (result.Error != null)
         {
             Util.LogError(result.Error);
             // Let's just try again
             FB.API(meQueryString, Facebook.HttpMethod.GET, APICallback);
             return;
         }
         
         profile = Util.DeserializeJSONProfile(result.Text);
         GameStateManager.Username = profile["first_name"];
         friends = Util.DeserializeJSONFriends(result.Text);
         checkIfUserDataReady();
     }
 
     void MyPictureCallback(Texture texture)
     {
         Util.Log("MyPictureCallback");
         
         if (texture ==  null)
         {
             // Let's just try again
             LoadPictureAPI(Util.GetPictureURL("me", 128, 128),MyPictureCallback);
 
             return;
         }
         
         GameStateManager.UserTexture = texture;
         haveUserPicture = true;
         checkIfUserDataReady();
     }
 
     private int getScoreFromEntry(object obj)
     {
         Dictionary<string,object> entry = (Dictionary<string,object>) obj;
         return Convert.ToInt32(entry["score"]);
     }
 
     void ScoresCallback(FBResult result) 
     {
         Util.Log("ScoresCallback");
         if (result.Error != null)
         {
             Util.LogError(result.Error);
             return;
         }
 
         scores = new List<object>();
         List<object> scoresList = Util.DeserializeScores(result.Text);
 
         foreach(object score in scoresList) 
         {
             var entry = (Dictionary<string,object>) score;
             var user = (Dictionary<string,object>) entry["user"];
 
             string userId = (string)user["id"];
 
             if (string.Equals(userId,FB.UserId))
             {
                 // This entry is the current player
                 int playerHighScore = getScoreFromEntry(entry);
                 Util.Log("Local players score on server is " + playerHighScore);
                 if (playerHighScore < GameStateManager.Score)
                 {
                     Util.Log("Locally overriding with just acquired score: " + GameStateManager.Score);
                     playerHighScore = GameStateManager.Score;
                 }
 
                 entry["score"] = playerHighScore.ToString();
                 GameStateManager.HighScore = playerHighScore;
             }
 
             scores.Add(entry);
             if (!friendImages.ContainsKey(userId))
             {
                 // We don't have this players image yet, request it now
                 LoadPictureAPI(Util.GetPictureURL(userId, 128, 128),pictureTexture =>
                 {
                     if (pictureTexture != null)
                     {
                         friendImages.Add(userId, pictureTexture);
                     }
                 });
             }
         }
 
         // Now sort the entries based on score
         scores.Sort(delegate(object firstObj,
                              object secondObj)
                 {
                     return -getScoreFromEntry(firstObj).CompareTo(getScoreFromEntry(secondObj));
                 }
             );
     }
 
     
     void checkIfUserDataReady()
     {
         Util.Log("checkIfUserDataReady");
         if (loadingState == LoadingState.WAITING_FOR_INITIAL_PLAYER_DATA && haveUserPicture && !string.IsNullOrEmpty(GameStateManager.Username))
         {
           Util.Log("user data ready");
           loadingState = LoadingState.DONE;
         }
     }
 
 
 
     void OnLevelWasLoaded(int level)
     {
         Util.Log("OnLevelWasLoaded");
         if (level == mainMenuLevel && loadingState == LoadingState.DONE)
         {
             Util.Log("Returned to main menu");
             // We've returned to the main menu so let's query the scores again
             if (FB.IsLoggedIn)
                 QueryScores();
         }
     }
 
     void OnApplicationFocus( bool hasFocus ) 
     {
       Util.Log ("hasFocus " + (hasFocus ? "Y" : "N"));
     }
 
     // Convenience function to check if mouse/touch is the tournament area
     private bool IsInTournamentArea (Vector2 p)
     {
         return p.x > Screen.width-tournamentWidth;
     }
 
 
     // Scroll the tournament view by some delta
     private void ScrollTournament(float delta)
     {
         scrollPosition.y += delta;
         if (scrollPosition.y > tournamentLength - Screen.height)
             scrollPosition.y = tournamentLength - Screen.height;
         if (scrollPosition.y < 0)
             scrollPosition.y = 0;
     }
 
 
     // variables for keeping track of scrolling
     private Vector2 mouseLastPos;
     private bool mouseDragging = false;
 
 
     void Update()
     {
         if(Input.touches.Length > 0) 
         {
             Touch touch = Input.touches[0];
             if (IsInTournamentArea (touch.position) && touch.phase == TouchPhase.Moved)
             {
                 // dragging
                 ScrollTournament (touch.deltaPosition.y*3);
             }
         }
 
         if (Input.GetAxis("Mouse ScrollWheel") < 0)
         {
             ScrollTournament (MouseScrollStep);
         }
         else if (Input.GetAxis("Mouse ScrollWheel") > 0)
         {
             ScrollTournament (-MouseScrollStep);
         }
         
         if (Input.GetMouseButton(0) && IsInTournamentArea(Input.mousePosition))
         {
             if (mouseDragging)
             {
                 ScrollTournament (Input.mousePosition.y - mouseLastPos.y);
             }
             mouseLastPos = Input.mousePosition;
             mouseDragging = true;
         }
         else
             mouseDragging = false;
     }
 
     //  Button drawing logic //
     
     private Vector2 buttonPos;  // Keeps track of where we've got to on the screen as we draw buttons
 
     private void BeginButtons()
     {
         // start drawing buttons at the chosen start position
         buttonPos = ButtonStartPos;
     }
 
     private bool DrawButton(string text)
     {
         // draw a single button and update our position
         bool result = GUI.Button(new Rect (buttonPos.x,buttonPos.y, ButtonTexture.width * ButtonScale, ButtonTexture.height * ButtonScale),text,MenuSkin.GetStyle("menu_button"));
       //  Util.DrawActualSizeTexture(ButtonLogoOffset*ButtonScale+buttonPos, ButtonScale);
         buttonPos.y += ButtonTexture.height*ButtonScale + ButtonYGap;
         
         if (paymentDialog.DialogEnabled)
             result = false;
 
         return result;
     }
 
 
 
     void OnGUI()
     {
         GUI.skin = MenuSkin;
         if (Application.loadedLevel != mainMenuLevel) return;  // don't display anything except when in main menu
 
         if (loadingState == LoadingState.WAITING_FOR_INIT || loadingState == LoadingState.WAITING_FOR_INITIAL_PLAYER_DATA)
         {
             GUI.Label(new Rect(0,0,Screen.width,Screen.height), "Loading...", MenuSkin.GetStyle("centred_text"));
             return;
         }
 
 
         
         BeginButtons();
         
        
             
         if(!FB.IsLoggedIn){
             if (GUI.Button(LoginButtonRect, "", MenuSkin.GetStyle("button_login")))
             {
 
                 FB.Login("public_profile,user_friends,email,publish_actions", LoginCallback);
             }
             GUI.Label(new Rect((Screen.width / 2) - 225, 100,450, 100), "Use the arrow keys to move Nubz", MenuSkin.GetStyle("centred_text"));
            }
 
         if (FB.IsLoggedIn)
         {
             if (DrawButton("Play"))
             {
                 onPlayClicked();
             }
 
             if (DrawButton ("Invite Friends"))
             {
                 onChallengeClicked();
             }
             if (DrawButton ("Highscore"))
             {
                 onHighScoreClicked();
             }
           /*  if (GameStateManager.Score > 0)
             {
                 if (DrawButton ("Brag")) 
                 {
                     onBragClicked();
                 }
             } */
 
         //    TournamentGui();
         }
 
         DrawPopupMessage();
             
     }
 
 
     public void AddPopupMessage(string message, float duration)
     {
         popupMessage = message;
         popupTime = Time.realtimeSinceStartup;
         popupDuration = duration;
     }
     public void DrawPopupMessage()
     {
         if (popupTime != 0 && popupTime + popupDuration > Time.realtimeSinceStartup)
         {
             // Show message that we sent a request
             Rect PopupRect = new Rect();
             PopupRect.width = 800;
             PopupRect.height = 100;
             PopupRect.x = Screen.width / 2 - PopupRect.width / 2;
             PopupRect.y = Screen.height / 2 - PopupRect.height / 2;
             GUI.Box(PopupRect,"",MenuSkin.GetStyle("box"));
             GUI.Label(PopupRect, popupMessage, MenuSkin.GetStyle("centred_text"));        
         }
 
     }
 
     void TournamentGui() 
     {
         GUILayout.BeginArea(new Rect((Screen.width - 450),0,450,Screen.height));
         
         Rect boxRect = new Rect();
 
         if(scores != null)
         {
             var x = 0;
             foreach(object scoreEntry in scores) 
             {
                 Dictionary<string,object> entry = (Dictionary<string,object>) scoreEntry;
                 Dictionary<string,object> user = (Dictionary<string,object>) entry["user"];
 
                 string name     = ((string) user["name"]).Split(new char[]{' '})[0] + "\n";
                 string score     = "Smashed: " + entry["score"];
 
                 boxRect = new Rect(0, 121+(TournamentStep*x)-scrollPosition.y , 100,128);
                 // Background box
                 GUI.Box(boxRect,"",MenuSkin.GetStyle("tournament_entry"));
                 
                 // Text
                 GUI.Label (new Rect(24, 136 + (TournamentStep * x) - scrollPosition.y, 100,128), (x+1)+".", MenuSkin.GetStyle("tournament_position"));      // Rank e.g. "1.""
                 GUI.Label (new Rect(250,145 + (TournamentStep * x) - scrollPosition.y, 300,100), name, MenuSkin.GetStyle("tournament_name"));               // name   
                 GUI.Label (new Rect(250,193 + (TournamentStep * x) - scrollPosition.y, 300,50), score, MenuSkin.GetStyle("tournament_score"));              // score
                 Texture picture;
                 if (friendImages.TryGetValue((string) user["id"], out picture)) 
                 {
                     GUI.DrawTexture(new Rect(118,128+(TournamentStep*x)-scrollPosition.y,115,115), picture);  // Profile picture
                 }
                 x++;
             }
 
         }
         else GUI.Label (new Rect(180,270,512,200), "Loading...", MenuSkin.GetStyle("text_only"));
         
         // Record length so we know how far we can scroll to
         tournamentLength = boxRect.y + boxRect.height + scrollPosition.y;
         
         GUILayout.EndArea();
     }
 
 
     //  React to menu buttons  //
 
 
     private void onPlayClicked()
     {
         Util.Log("onPlayClicked");
 
 
 
         Application.LoadLevel("level1");
         GameStateManager.Instance.StartGame();
     }
 
     private void onHighScoreClicked ()
     {
         Application.LoadLevel("highScore");
     }
 
     private void onBragClicked()
     {
         Util.Log("onBragClicked");
         FB.Feed(
                 linkCaption: "I just smashed " + GameStateManager.Score.ToString() + " friends! Can you beat it?",
                 picture: "http://www.friendsmash.com/images/logo_large.jpg",
                 linkName: "Checkout my Friend Smash greatness!",
                 link: "http://apps.facebook.com/" + FB.AppId + "/?challenge_brag=" + (FB.IsLoggedIn ? FB.UserId : "guest")
                 );
     }
     private void onChallengeClicked()
     {
             FB.AppRequest(
                 to: null,
                 filters : "",
                 excludeIds : null,
                 message: "Friend Smash is smashing! Check it out.",
                 title: "Play Friend Smash with me!",
                 callback:appRequestCallback
                 );
      //   }
     }
     private void appRequestCallback (FBResult result)
     {
         Util.Log("appRequestCallback");
         if (result != null)
         {
             var responseObject = Json.Deserialize(result.Text) as Dictionary<string, object>;
             object obj = 0;
             if (responseObject.TryGetValue ("cancelled", out obj))
             {
                 Util.Log("Request cancelled");
             }
             else if (responseObject.TryGetValue ("request", out obj))
             {
                 AddPopupMessage("Request Sent", ChallengeDisplayTime);
                 
                 Util.Log("Request sent");
             }
         }
     }
     
 
     public static void FriendPictureCallback(Texture texture)
     {
         GameStateManager.FriendTexture = texture;
     }
 
     delegate void LoadPictureCallback (Texture texture);
 
 
     IEnumerator LoadPictureEnumerator(string url, LoadPictureCallback callback)    
     {
         WWW www = new WWW(url);
         yield return www;
         callback(www.texture);
     }
     void LoadPictureAPI (string url, LoadPictureCallback callback)
     {
         FB.API(url,Facebook.HttpMethod.GET,result =>
         {
             if (result.Error != null)
             {
                 Util.LogError(result.Error);
                 return;
             }
 
             var imageUrl = Util.DeserializePictureURLString(result.Text);
 
             StartCoroutine(LoadPictureEnumerator(imageUrl,callback));
         });
     }
     void LoadPictureURL (string url, LoadPictureCallback callback)
     {
         StartCoroutine(LoadPictureEnumerator(url,callback));
        
     }
 
 }
Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image smallbit · Aug 12, 2014 at 05:42 PM 0
Share

Than do the opposite , remove DontDestroyOnLoad (gameObject); from every script. In this script here is in line 147

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

22 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Application.LoadLevel(Application.loadedLevel); wont work While checkpoints are on 3 Answers

Multiple Cars not working 1 Answer

Distribute terrain in zones 3 Answers

Change scene and play it by clicking UI Button? Scene does just load but not start playmode? 1 Answer

[C#] Do not load scene yet 2 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges