本文介绍了如何使用从前一个场景中选择的一个对象到当前场景?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一款 FPS 游戏.我在主菜单场景中的第一个场景.这很好.在第二个场景中,用户正在选择他想要使用的枪(有四把枪).当他按下播放键时,我正在加载新场景(gamePlay).我如何跟踪用户选择的枪?那么,他可以在游戏中使用那把枪吗?当您通过切换相机在单个场景中工作时,这很容易.但是在新场景中怎么做呢?

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?

推荐答案

这就是我一直在做的,而且效果很好.

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

实现一个派生自 MonoBehaviour 的单例来保存用户在菜单之间的选择,并且在加载新关卡时不会被破坏.

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.

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);
         }
     }
}

现在您只需要做一次:

  1. 创建一个空的游戏对象
  2. 将此脚本附加到它,然后将其保存为预制件
  3. 在每个需要它的场景中也拖动它

现在您可以轻松保存和阅读用户在场景之间的选择:

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;

顺便提一下,我通常创建属性而不是简单地访问公共变量,因为我喜欢控制分配的值(验证、额外行为等...)

MonoBehaviour

DontDestroyOnLoad

这篇关于如何使用从前一个场景中选择的一个对象到当前场景?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-05 05:27