Unity3D/C#: Scene Transitions

One thing folks will probably notice in Unity3D is that when you change scene your character may not be loaded, or you may decide to add your character to every scene file, but if you’ve got data you want to retain between levels, that method doesn’t really work.

Unity3D offers you the ability to prevent any chosen objects from being destroyed on loading. This command is called:

DontDestroyOnLoad(GameObject);

What you should do is use it inside of a script attached to an object you don’t want destroyed. For example, I have PlayerStats.cs. This command should sit in your awake method.

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

Now this presents itself with a few other issues. For example, how your Player object will interact with the scene, like your ‘pick up object’ script might not work because it relies on you dragging and dropping your player into the ‘GameObject’ field. All you need to do is adjust your script. This is also where tagging really helps (tag your player object in the editor with ‘Player’).

So instead of dragging and dropping your player in the editor to attach it to your GameObject variable. Instead, you’ll have your scripts look for an object tagged with ‘Player’ and assign that instead.

GameObject player = GameObject.FindGameObjectWithTag(“Player”);
Player = player;

The other issue is placing your player in the right spot in the scene. What you need to do is create a GameObject called ‘SpawnPoint’  and in the SpawnPoint’s script you’ll need to use your awake method.

void Awake()
{
GameObject player = GameObject.FindGameObjectWithTag(“Player”);
Player = player;
Player.transform.position = SpawnPoint.transform.position;
}

Your player will appear wherever you stick the spawn point. If you want to complicate things you can use an array of spawn points as you might if you’ve got multiple entrances and exits. But for this tutorial, it’ll just be simple. 🙂

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s