Search code examples
unity-game-enginescene

How to use one object selected from previous scene to the current scene?


I am working on a FPS game. I which my first scene in Main menu scene. Which is fine. In the second scene user is selecting the gun which he want to use (There are four guns). When he press play i am loading the new scene(gamePlay). How can i keep track of the gun which the user selected? so, he can use that gun in the gamePlay? its easy when you are working in a single scene by switching your camera. But how to do it in the new scene?


Solution

  • This is how I have been doing and it works really well.

    Implement a Singleton that derives from MonoBehaviour to hold user choices between menus and that will not be destroyed when a new level is loaded.

    Singleton example

    public class UserChoices : MonoBehaviour 
    {
        public static UserChoices Instance = null;
    
        // just an example, add more as you like
        public int gun;
    
        void Awake()
        {
             DontDestroyOnLoad(this.gameObject);
             if(Instance == null)
             {
                 Instance = this;
             } else if(Instance != this)
             {
                 Destroy(this.gameObject);
             }
         }
    }
    

    Now you just need to do this once:

    1. Create an empty GameObject
    2. Attach this script to it and then save it as a prefab
    3. Drag it too every scene that needs it

    Now you can save and read the user choices between scenes easily:

    // read chosen gun
    int chosen_gun = UserChoises.Intance.gun;
    
    //save chosen gun
    UserChoises.Intance.gun = PlayerGuns.Knife;
    

    Just a side note, I usually create properties instead of accessing simply public variables because I like to control what values are assigned (validation, extra behaviors, etc...)

    References:

    MonoBehaviour

    DontDestroyOnLoad