0

I am new to C# and been trying to make a 2D platformer game by learning specifically what I need. I am kinda stuck atm.

I have tagged the Door with "Next" and programmed the player to enter "level 2" scene when it collides with anything tagged with "Next".

I want the player to obtain a Key before this script can take effect, and i have no idea how to code it.

I know this isn't the most optimal code, but this is what I used to make the game load next level

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

Help will be much appreciated.

1 Answer 1

3

You can add a boolean called bool key = false; and then set it to true the moment you pick up the key.

Key PickUp (lies on Player GameObject)

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

When you've done that you can just ask if the player has a key when he enters the door, if he doesn't have a key he can't enter.

Door Enter Example (lies on Player 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);
    }
}

To use the the Code shown above you would need to make the Key a GameObject with a Collider that has IsTrigger set to Active. As well as adding both Code parts into your Player Script where you are already detecting the Collision right now.

0

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.