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 don’t want to destroy your game objects – you want to preserve them between scenes. The way to do it is incredibly simple.

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);
}

The simplest way to implement it is to have a single script called DontDestroy and attach it to every game object you don’t want to destroy. This makes your project much tidier.

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

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

Now 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 in 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.

 

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