In this article, we are going to create behaviors that require the player to collect all of the coins and a key before being allow to activate the elevator button. If the player tries to activate the elevator without all of the coin and key, the elevator button will not work.
Accessing the Player Script
On the Player script we are keeping track how many coins the player has collected. So when the player presses the elevator call button we will need to check the amount of coins the player currently has. We can do this since the OnTrigger allows for us to access the Player script through “other”. We will create a Player variable and store the Player component, so we can access the script when we call the elevator.
Checking Coin Amount
We are already tracking the amount of coins in the Player script, so when the player calls for the elevator, we will need to let the Elevator script know what the coin count current is by using a public int method and return the coin count.
Back on the Elevator script, when the call button is pressed, the CoinCount method returns the amount of coins the player currently has and if it the amount needed then the elevator will be called.
In making the script more modular, we can declared a int variable and serialize it so the Game Design can determine in the Inspector the amount of coins the player needs to collect before accessing the elevator.
I wanted to take this one step further by creating a key the player also needs to collect before accessing the elevator.
In the Player script, we are going to create a bool variable to track if the player has collected the key. A method is needed, so when the player collides with the key this method can be called. This method simply set our hasKey bool to True.
On the Key script, we are going to use a OnTriggerEnter and we will check to see if the tag is Player. If it is, we will grab the Player script through the other and call the CollectedKey method that sets the hasKey bool to True.
Going back to the Player script, we are going to create a bool method that will return current status of that variable. This is need so when we call the Elevator we can check to see if the bool is True meaning the key has been collected.
In the Elevator script, we modify the script to check to see if the has the key by using calling the bool method that returns the status of the hasKey bool.
In the next article, we will cover the Elevator moving down when the button is pressed. Cheers!