Some doors just need a Key
In the Common Interactions with Interfaces blog post, we created a functionality where the player can open or close a door by pressing the E key.
In today’s blog post, let’s expand this feature further by adding locking and unlocking functionality to our doors.
Adding a door control panel
In most video games, you’ll see a door control panel that tells you whether a door is locked or unlocked. Let’s add one to our doors.
I created a child empty GameObject for one of our doors and added two control panel GameObjects: one for the locked state and the other for the unlocked state. We can toggle between these two panels to show whether a door is locked or not. I’ll have it start locked, requiring the player to unlock it.
Scripting
In the Door script, let’s add a boolean to determine the door’s state and a GameObject for the door control panel:
[SerializeField] private bool _isLocked;
[SerializeField] private GameObject _doorControlPanel;
The door control panel has two child GameObjects. We can use the _isLocked variable to decide which panel to show at the start of the game:
void Start()
{
if(_isLocked)
{
_doorControlPanel.transform.GetChild(0).gameObject.SetActive(true);
_doorControlPanel.transform.GetChild(1).gameObject.SetActive(false);
}else
{
_doorControlPanel.transform.GetChild(0).gameObject.SetActive(false);
_doorControlPanel.transform.GetChild(1).gameObject.SetActive(true);
}
}
Now, let’s update the Interact method so that when a door is unlocked, we can open it by pressing the E key. If the door is locked, a message will be logged to the console:
public void Interact()
{
if (!_isLocked)
{
_isOpen = !_isOpen;
_anim.SetBool("IsOpen", _isOpen);
} else {
Debug.Log("Door is locked");
}
}
Testing
I’ll test two doors. For door 1, I’ll have it unlocked by unchecking the Is Locked checkbox, and I’ll leave door 2 locked. Here’s the result:
As you can see, we can open the first door, while a message is sent to the console when the player tries to open the second one. In the next blog post, we’ll add a feature to unlock our doors using the terminal.