During my 3rd person shooter game development, I have planned to have 3 pairs of door switch to create the tense of game environment, which is inspired by Resident Evil series. Therefore, having a door switch system is quite important to this project. Without searching for any ideas, I decides to design one on my own.
In this tutorial, I would create a door switch system to pair up a button and a door in 3D game.
To create this system, we simply need a parent object as controller, and 2 child objects: door and button.
In this system, parent object would handling the script. While Player is approaching button and pressed the specific button, it would make the door open.
Create a script and add it into the parent object.
First, we need 2 gameobject variables to locate the button and door; and also a float to set the speed of door moving when open; then a bool as switch to trigger the door to open.
In this script we would only need 2 methods: Update() and OnTriggerStay().
In Update(), let’s check if the button is presses by using the bool.
If so, we need to make the door moves on a specific axis till the position we want.
Next is OnTriggerStay(), in this method we would check if Player has approached and pressed the specific key. If so, we can simply switch the value of bool to trigger the door.
And to prevent unexpected collision between colliders, we can disable the collider of door for a smooth door opening effect.
That is all of creating this script.
Tips of collider & rigidbody
Notice that OnTriggerStay() would only available with a rigidbody component. You would need a rigidbody in your parent object, otherwise your trigger detection might not works.
As for the door, you can also create a rigidbody to it and set freeze to all position and rotation except the position that it would move.
And this is how I create a system to open a door.