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
1
Question by armandas2005 · Jun 21, 2021 at 06:15 PM · gameobjectdontdestroyonload

DontDestroyOnLoad isnt working

I have created a script which creates an object and brings it to another scene. Up to this point everything works, but if I use my Restart () function (if I've lost the game) this object is simply gone. The object has a DontDestroyOnLoad function and the Restart () function has that.

The object is created during the transition into the game scene, in the Play () function

 public void Play()
     {
         Instantiate(Skins.itemList[MySkins.selectedSkin].Object, transform.position, transform.rotation);
         SceneManager.LoadScene("Game");
     }

When the new scene is loaded, the object is made as a child of the Player Object and its position is reset in the Start () method

 void Start()
     {
         transform.position = Vector3.zero;
     }
     // Update is called once per frame
     void Update()
     {
         if (PlayerHolder == null)
         {
             PlayerHolder = transform.Find("/Player");
         }
         if (PlayerHolder != null)
         {
             transform.SetParent(PlayerHolder);
         }
     }

So far everything works, but if I die in the game and use the restart function, the object is simply gone.

  void Awake()
     {
         _Player = GameObject.FindGameObjectWithTag("Playerr");
     }
     public void Restart()
     {
 
         DontDestroyOnLoad(_Player);
 
        SceneManager.LoadScene("Game");
 
     }

The object also has a DontDestroyOnLoad script

     public void Awake()
     {
         DontDestroyOnLoad(this.gameObject);
     }

I appreciate any help and hope that someone can help me with the matter and thank everyone who tries to help.

Comment
Add comment · Show 1
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 Janette5 · Jun 22, 2021 at 05:48 AM 0
Share

There could be a problem with how you're switching scenes - I can't quite work it out from what you gave. If you're creating the object when transitioning, then what happens when you restart? Are you creating that object again? You could try modifying your code like this:

         if (instance == null)
         {
             instance = this;
         }
         else if (instance != this) //in case there is already one - safety check
         {
             Destroy(gameObject);
         }
 
         DontDestroyOnLoad(gameObject); //singleton - don't destroy

There might be a better way of handling the situation - like saving the data you need in your Game Manager script, if you're using one. Then you would create it once as the game starts and keep it active, in which case you won't have a problem with it being created again.

1 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by Proliecan · Jun 23, 2021 at 10:09 AM

Hey @armandas2005

I would recommend using the Singleton pattern.

You would use a baseclass that guarantees there is only one Instance of an Object at a time.


The code for the baseclass is:

 using UnityEngine;
  
 /// <summary>
 /// Inherit from this base class to create a singleton.
 /// e.g. public class MyClassName : Singleton<MyClassName> {}
 /// </summary>
 public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
 {
     // Check to see if we're about to be destroyed.
     private static bool m_ShuttingDown = false;
     private static object m_Lock = new object();
     private static T m_Instance;
  
     /// <summary>
     /// Access singleton instance through this propriety.
     /// </summary>
     public static T Instance
     {
         get
         {
             if (m_ShuttingDown)
             {
                 Debug.LogWarning("[Singleton] Instance '" + typeof(T) +
                     "' already destroyed. Returning null.");
                 return null;
             }
  
             lock (m_Lock)
             {
                 if (m_Instance == null)
                 {
                     // Search for existing instance.
                     m_Instance = (T)FindObjectOfType(typeof(T));
  
                     // Create new instance if one doesn't already exist.
                     if (m_Instance == null)
                     {
                         // Need to create a new GameObject to attach the singleton to.
                         var singletonObject = new GameObject();
                         m_Instance = singletonObject.AddComponent<T>();
                         singletonObject.name = typeof(T).ToString() + " (Singleton)";
  
                         // Make instance persistent.
                         DontDestroyOnLoad(singletonObject);
                     }
                 }
  
                 return m_Instance;
             }
         }
     }
  
  
     private void OnApplicationQuit()
     {
         m_ShuttingDown = true;
     }
  
  
     private void OnDestroy()
     {
         m_ShuttingDown = true;
     }
 }

(Source)

To use it, you inherit the class from Singleton Instead of MonoBehaviour:

 [DisallowMultipleComponent]
 public class Example : Singleton<Example>
 {
     //Normal MonoBehavour Code Here
    public int someInteger = -1;
 }

It automatically is a MonoBehaviour and exactly one Instance is accessible at alltimes - not more and not less.

To access this Instance you refer to the static .Instance variable:

 void AccessExampleSingleton()
 {
     Debug.Log(Example.Instance.someInteger.ToString());
 }

That's all you have to do to have a perfectly smooth running system. I would personally recommend the Singleton-Pattern for all kinds of game managers, resource managers, pooling managers, player objects and so on. Everything that is persistent throughout the game should use this base class to avoid complicated bugs when introducing the object to the scene and removing it again, transporting it between scenes and avoiding multiple Objects. On top, it is good practice and clean code.

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

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

182 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 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 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 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 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 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 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 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 avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

How to run a function in a GO that have DontDestroyOnLoad 1 Answer

Setting public GameObject to a different Prefab through code 0 Answers

DontDestroyOnLoad error 2 Answers

DontDestroyOnLoad Slowing Loading Down 0 Answers

game object is not being destroyed 1 Answer


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