【问题标题】:Unity2D Platformer: Player needs a key before using DoorUnity2D Platformer:玩家在使用 Door 之前需要一个钥匙
【发布时间】:2020-08-08 19:08:26
【问题描述】:

我是 C# 新手,我一直在尝试通过专门学习我需要的东西来制作一款 2D 平台游戏。我有点卡在自动取款机上。

我已经用“Next”标记了门,并编程让玩家在它与任何带有“Next”标记的东西发生碰撞时进入“2 级”场景。

我想让玩家在这个脚本生效之前获得一个Key,我不知道怎么编码。

我知道这不是最优化的代码,但这是我用来让游戏加载下一关的代码

private void OnTriggerEnter2D(Collider2D other)
    
if (other.gameObject.CompareTag("Next"))
     { SceneManager.LoadScene("Level 2");}

我们将不胜感激。

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    您可以添加一个名为 bool key = false; 的布尔值,然后在您拿起密钥的那一刻将其设置为 true。

    Key PickUp(位于玩家游戏对象上)

    private void OnTriggerEnter2D(Collider2D other) {
        if (other.gameObject.CompareTag("Key")){
            // Key has been collected
            key = true;
            // Destroy Key after we've collected it
            Destroy(other.gameObject);
        }
    }
    

    完成后,你可以在玩家进门时询问玩家是否有钥匙,如果没有钥匙则无法进入。

    门进入示例(位于玩家游戏对象上)

    private void OnTriggerEnter2D(Collider2D other) {
        // Checking if Player Entered the Door Trigger and if he collected a key
        if (other.gameObject.CompareTag("Next") && key) {
            // Key was "used"
            key = false;
            // Load Scene next in the BuildIndex Order
            SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
        }
    }
    

    要使用上面显示的代码,您需要将 Key 设为 GameObject,其中包含将 IsTrigger 设置为 Active 的 Collider。以及将这两个代码部分添加到您现在已经检测到Collision 的播放器脚本中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-15
      相关资源
      最近更新 更多