Moving game objects between scenes

Hi, everyone

I have created a simple platformer game in Unity. I have created a key that when collected unlocks a door later in the game. I have made a simple variable checking if the player has found the key and then deactivates it. I use the scene manager to load the levels. Whenever I enter a new scene the script that is attached to the key and the key is gone. Is there any way to move the gameObject through scenes or to have the game check if the key is collected? Thank you for any answers.

Here ya go :slight_smile:

1 Like

Thank you! It works, but I cannot destroy the door because the key and the door are in seperate scenes and I don’t know if I can reference the door in the other scene to destroy it. Do you have any ideas?

Don’t destroy some other object (player?) which has a field “hasKey.” Recreate the key gameobject if you need it again. Probably you don’t need to visualize it again depending on type of game. Just let player enter locked room if hasKey = true. (Or perhaps list of key integer ids if many keys)

I think is better to check if the key is collected. There are couple of ways and some more advance coders. Easiest way would be using playerprefs or just make your bool variable static.

What is a static variable? I am new to unity and c#.

I dont really use it as much. Its something you should be really careful of using when you make something static. It means you’re creating a instance that any scripts can change and it lives throughout your game even if u change scenes. You probably have seen this commonly used in singletons.

Heres an example and dont put this script in your scene:

 public static class PlayerData
{
     public static bool bossDoorLock = true;
}

You can put this script in your scene

public class BossDoorController: MonoBehaviour
{

    private void OnTriggerEnter2D(Collider2D other)
    {
        if (other.gameObject.CompareTag("Player"))
        {
             Player player = other.GetComponent<Player>();

            // If player has key, unlock this door
            if (player.HasBossKey)
                 PlayerData.bossDoorLock = false;

            // If door is not locked
            if(!PlayerData.bossDoorLock)
                 // Open door code here
        }
    }
}