Reputation: 45
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.
Upvotes: 0
Views: 432
Reputation: 2974
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.
Upvotes: 3