从 Unity 中的另一个脚本访问 public bool

问题描述 投票:0回答:2

我正在寻找从另一个脚本在 LevelManager 脚本中触发公共 bool 设置。

所以当脚本 B 发生某些事情时,脚本 A 中的 bool 切换为 true。

下面是 2 个脚本,其中 levelRestart.cs 是一个触发器,当玩家点击时,它需要访问 LevelManager 脚本中的 public bool 并说

startGame
为真。

有人可以帮忙吗?

LevelManager.cs

public bool startGame = false;

void Update ()
    {

        if (startGame == true)
        {
            SpawnKonyaku();
            startGame = false;
        }
    }

LevelRestart.cs

void OnTriggerEnter2D(Collider2D col)
    {
        if (col.gameObject.tag == "Player")
        {            
            levelManager.startGame = false; //<- This is where, i need help    
        }
    }

RestartLevel 脚本触发 public bool startGame 为真

unity3d
2个回答
0
投票

好吧,我自己想出来了,我要把答案写在这里,添加到那里的许多其他脚本问题中。

我添加了这些变量以从脚本 A 中提取

public GameObject _LevelManager;
private LevelManager script;`

比我在 Void Start 上添加的

void Start ()
{
    script = _LevelManager.GetComponent<LevelManager>();
}

当我运行 triggerenter 方法时,它实际上调用了 bool

public void OnTriggerEnter2D(Collider2D col)
{
    if (col.gameObject.tag == "Player")
    {            
        script.startGame = true;         
    }
}

0
投票

您可以通过将其保持为静态来触发 bool startGame,即 public static bool startGame。这样就可以直接用 LevelManager 触发了。

© www.soinside.com 2019 - 2024. All rights reserved.