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

梦想的初衷 提交于 2019-12-11 04:07:58

问题


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?


回答1:


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




回答2:


You can set the GameObjects that the user is selecting to not be automatically destroyed. Take a look at DontDestroyOnLoad.

This way they get preserved when changing scenes.

You'll probably need to be make them inactive while in the selection screens.



来源:https://stackoverflow.com/questions/22837395/how-to-use-one-object-selected-from-previous-scene-to-the-current-scene

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!