DontDestroyOnLoad *crashes unity*

I instantiate a prefab, then exit the game. I am then presented with the exitgame scene (which shows players stats), I pause, and see that my prefabs that I do not want to DestroyOnLoad are visable in the inspector, I click on them and the mesh isn’t there (it is invisable) but the boxcollider (along with the rest of the components) are present. Then I press ‘esc’ to load another scene and it crashes; Unity Completely exits and I am at the desktop…

Nothing unusual is attached to this prefab that I am instantiating. The Transform component comes for free, I have a rigidbody, AudioSource, and BoxCollider Components.

Should I be saving the position in PlayerPrefs instead? Could Someone help?

    public class ThisScriptMostLikelyCrashesUnity : MonoBehaviour {
        private void Awake() { 
            //DontDestroyOnLoad(this); //This crashes Unity
            DontDestroyOnLoad(transform.gameObject); //This also crashes Unity
        }
        //this script is attatched to the object that is instantiated.
    }

bump, I don’t know what’s causing the problem?

I use the DontDestroyOnLoad line outside of any classes or functions on it’s own as a separate script attached to an object, when it makes my projects get buggy, seems to work

I use this with no problems, but it’s pre-attached to a Manager object. I think your problems are coming from instantiating since you can’t predict even what order scripts/components are added.

using UnityEngine;

public class DontDestroy : MonoBehaviour
{
	void Awake()
	{
		DontDestroyOnLoad(this);
	}
}

Upon further analysis of the problem:

  1. Only Instantiate one prefab (I was instantiating like 10)

It doesn’t crash, however when I come back into the game on a different team, the prefab is invisable! Then if I exit it will crash in the same way as before (a scene earlier)! The prefab has a child object (this is because I made a group in 3Ds Max before I exported).

it doesn’t work when I attach the script that has DDOL(this) or DDOL(transform.gameObject) in void Awake(){} on either the child or the parent or both…These problems only seem to happen to me…

Thanks for the responses guys :wink:

I don’t know what to do about this…DDOL works fine with music…but if I need to instantiate a FBX Import (that I dragged into a prefab), it crashs or I can’t see it.