Creating a Door Interactable Using the Interface In Unity3D.
Objective: Creating a Door Interactable Using the Interface In Unity3D.
Create a script called Interactable, and attach it to the door.
Create an Interface called IInteractable and create two methods: Interact and Activate.
Go to the Interactable script, create these three variables of these types.
You may be wondering where this UIContainer comes from?
Our door has a sphere collider to detect a trigger, and inside the doo,r we have UIText to show player which button to press, so that container we will use to enable and disable the text when player are inside the range or collider.
Create an Awake method and disable the text, set isLocked to false, and get the IIInteractable for the door.
But Suleiman, where is the IInteractable for the door? We dont have a Door script?
Yes, we dont have a door script, yet.
Now create the Door script and attach it to the Door, the Inherit IInteractable.
Inside the Door script, create these variables and get animotor from the Awake method.
Note: It is very important to get the component from Awake, but you won't get an error if you get the component in the start method if the object is in the scene, but you will get an error if the object is instantiated due to method call order.
Official Link for the method execution order for Unity
Go interact method and check if isLocked is equal to false, then open the door or close the door if the Interact method is called again, if _isLocked is true, tell the player what to do.
Note: I am not going to explain where is Interact method comes from. I assume you know what an interface is and what will happen when you inherit it.
Now go to Interactable script, create use OnTriggerEnter and OntriggerExit, to turn UI and _isInteractable to true or false, if the player is in range or off the Range of the door collider.
Create Update method inside Interactable script, then check for E Input and if _isInteractable bool is true. If the Condition is met, please call the Interact method using the _interactable variable we created earlier from the top of the Interactable script.
Note: We use this bool to make sure we call this method once to avoid calling this method many times.
Now select the door and make sure sphere collider is set to isTrigger, and the Door script and Interactable are attached. Then, drag and drop the UI Container to its field in the inspector.
Note: _isLocked is set to false from Inspector; this door will not need any key or other way to open it. Plus, I won't talk about how I set the animator control and animation, etc. I believe you are an intermediate or advanced user. If you are not, please search my article for that topic.
This is how I create a door Interactable using Interface.
See you in the next one.
