简体   繁体   English

如何从一个脚本访问布尔值到另一个脚本,以便在多个场景中加载?

[英]How to access a bool from one script to another so I can load in multiple scenes?

I'm a noob at unity and I'm trying to make a game where you come to an area and when you walk over an invincible box I have placed another scene loads in. And it will keep on going like that.我是一个团结的菜鸟,我正在尝试制作一个游戏,当你来到一个区域时,当你走过一个无敌的盒子时,我已经放置了另一个场景加载。它会继续这样下去。 In every scene you load in there will be another box to load the next scene in. But it will also unload scenes that are not directly behind you.在您加载的每个场景中,都会有另一个框来加载下一个场景。但它也会卸载不在您身后的场景。 So i you where to walk forwards, you would load 2 scenes infron of you and have 1 scenes loaded behind you.所以我你往哪里走,你会在你面前加载 2 个场景,在你身后加载 1 个场景。 I have done this since my game lags because of the amount of assets I have in the game and the graphics on them.我这样做是因为我的游戏因为我在游戏中拥有的资产数量和它们上的图形而滞后。

If it helps I'm using HDRP to make this game and all scenes are in front of each other so there is no bend to the map.如果它有帮助,我正在使用 HDRP 制作这个游戏,并且所有场景都在彼此的前面,所以地图没有弯曲。

What I have come up with so far is using the box and adding a trigger on it to activate a bool that will load the next scene in a different script since that script has already a part where it loads a scene.到目前为止,我想出的是使用该框并在其上添加一个触发器来激活一个布尔值,该布尔值将在不同的脚本中加载下一个场景,因为该脚本已经有一个加载场景的部分。

Any ideas on how to solve it or how to get the bool component from one script to another since it is triggered by a box collider.关于如何解决它或如何将 bool 组件从一个脚本获取到另一个脚本的任何想法,因为它是由盒子对撞机触发的。 So when the box collider gets triggered you set the bool to true and the next scene loads in.因此,当 box collider 被触发时,您将 bool 设置为 true 并加载下一个场景。

you can use a Singleton pattern to send and keep data between scene.您可以使用单例模式在场景之间发送和保存数据。 Here is one template has you didn't put code.这是您没有输入代码的一个模板。

public class GameManager : MonoBehaviour
  {
      public static GameManager Instance;
      public bool myBool; //here you can declare all the things you want

  
      void Awake()
      {
  
          if (instance != null && instance != this)
              Destroy(this.gameObject);
          else
          {
              instance = this;
              DontDestroyOnLoad(gameObject); //allow the script to not be destroyed when switching scene
          }
      }
  }

Then, if you want to call this class from another class you just have to do this :然后,如果你想从另一个类调用这个类,你只需要这样做:

GameManager.Instance.myBool;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM