How To Not Destroy Objects Between Scenes – Unity C#

When you load a new scene in Unity, it destroys all of your objects. Sometimes, though, you want to preserve them between scenes. I’ll show you how. This is something I did frequently in my game Puzzledorf, as I had a number of objects loaded in the first scene that I wanted available in every scene, particularly if they held certain scripts / information I wanted to be able to access at all times.

How To Do It

If you want to preserve a game object between scenes, you need to have a script attached to it, then add the following line of code:

private void Awake()
{
  DontDestroyOnLoad(gameObject);
}

So long as that line of code is in a script attached to the game object, it won’t get destroyed between scenes. But there’s a nice way to do it to make things tidy.

Create a single script called DontDestroy and attach it to every game object you don’t want to destroy.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

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

Whenever you attach that script to an object, it won’t be destroyed. Try it. There are, however, some pitfalls, listed below.

gameObject written like this refers to the game object that this script is attached to.

Awake is a function like Start, however, it will only ever run once when the object is created, Awake runs before Start, and Awake runs even if the script is inactive (but the game object has to be active). Read more about Awake here.

Pitfalls

So far I have found two cases where DontDestroyOnLoad() does not work, but they’re easy to work around. They are:

  • If a game object is deactivated in the game editor
  • If a game object is deactivated during the Awake function

The solution is, anything you want to keep between scenes, leave it active in the editor, and to deactivate it, do it in a script inside Start rather than Awake. That fixes it for some reason.

If you enjoyed reading, try my game Puzzledorf out on Steam and Humble Bundle.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Blog at WordPress.com.

Up ↑

%d bloggers like this: