问题
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:
- Create an empty GameObject
- Attach this script to it and then save it as a prefab
- 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