OPENING a DOOR with a KEY! (Unity Beginner Tutorial)
Вставка
- Опубліковано 21 сер 2024
- In this Unity C# tutorial I show you how to code picking up a key, interacting with a door and opening and closing with animations - Using a basic raycast and controller scripts, creating a basic inventory and adding more functionality and timers to stop spamming of door interactions!
➡️Playing and Creating Animations: • Creating SIMPLE Animat...
➡️Creating a Crosshair UI: • Creating a Crosshair i...
➡️Door Interaction Kit: • Door Interaction Kit -...
🎁 Get OVER 160+ Scripts, Projects and premium content on my PATREON HERE:
➡️bit.ly/SpeedTut...
·························································································
🔥 INSANE UNITY SAVINGS: bit.ly/UnitySa...
🕹️Synty Publisher Mega Sale: bit.ly/SyntyPu...
🕹️SpeedTutor Unity Store: bit.ly/STUnity...
🕹️Unity New Release Discount Sale: prf.hn/l/BdvEmg3
🕹️Unity WELCOME2022 Offer: bit.ly/UnityWe...
🔥 INSANE HUMBLE SAVINGS: bit.ly/HumbleB...
🕹️Humble Tutorial Bundle: bit.ly/Mammoth...
🕹️Unity ART Bundle: bit.ly/UnityHu...
🕹️Unity TOOLS Bundle: bit.ly/UnityIn...
🕹️SFX for Games Bundle: bit.ly/SFX-Mus...
🕹️Learn Programming Games Bundle: bit.ly/LearnPr...
🔥Unity Materials / Files & More:
🕹️CGAxis 400 PBR Material Bundle: bit.ly/CGAxisP...
🕹️Synty Assets: bit.ly/SyntyLo...
🕹️Filebase Assets: filebase.gamed... (Code: SPEEDTUTOR2022 - Sign up for a FREE MONTH)
🔥 UNITY SUBSCRIPTIONS:
🕹️Unity Plus: bit.ly/UnityPl...
🕹️Unity Pro: bit.ly/UnityPr...
·························································································
💰BIG DISCOUNTS on my website, for my UNITY ASSETS:
➡️www.speed-tuto...
💬Join the Community Discord:
➡️ / discord
💝 Make a donation to the channel:
➡️www.paypal.me/s...
·························································································
⬇️ SpeedTutor Puzzle Assets:
➡️Unity Store: bit.ly/STUnity...
➡️My Website Discounts: www.speed-tuto...
⬇️ SpeedTutor Best Selling Assets:
🧩Adventure Puzzle Kit: bit.ly/STAdven...
🗒️ Note & Letter System: bit.ly/STNoteL...
🔍Examine System: bit.ly/STExami...
🔢Keypad System: bit.ly/STKeypa...
⬇️SpeedTutor Model Packs:
➡️Unity Store: bit.ly/STUnity...
➡️My Website Discounts: www.speed-tuto...
My Assets include: Gas Mask, Flashlight, Generator, Themed Key , Padlock, Phone, Chess Puzzle, Lever, Valve Puzzle, Fuse Box & Safe Systems. Cardboard, Debris, Massive Models and more!
························································································
⭐ Connect with me:
💬| Discord: / discord
🐦| Twitter: / speedtutor
📱 | Facebook: / speedtutoruk
🖥 | Website: www.speed-tutor...
·······················································································#SpeedTutor #Unity #DoorKey
Lets find the keys to unlock your potential! Lets learn together today. :)
🔥UNITY SAVINGS: bit.ly/UnitySalesHub
🔥SpeedTutor Unity Store: bit.ly/STUnityStorePuzzlePacks
🔥HUMBLE SAVINGS: bit.ly/HumbleBundleDeals
I hope you guys find the tutorial useful! :) Do let me know if you have any new suggestions!
very useful! Thx a lot of.
Thank you so much you don't understand how long this has taken me to figure out
I'm glad you've found this helpful! :D
TYSMMMM i had some problem with the animations but now its working perfectly!!!
Fantastic! I'm really glad to hear it, thanks for coming along to watch! :D
I just bought your themed key door Unlock System Asset which is obviously better and less time waste😂 Thanks mate for your wonderful tutorials and great videos!
Haha, thanks so much my friend. I really appreciate that! :)
Been waiting for this for so long i was forced to steal the code instead of making it
It's finally here! :)
thx so much my friend!!! Congratulations for 100 K
subscriber!!!
Thanks very much! :D
you took so much time since u released the asset but finally its out :)
I know! Haha, I'm sorry. I did the other 4 I think but this one got lost!
Always so well explained man, appreciate it!
No worries at all, I'm glad you think so! :)
Thank you so much! Amazing tutorial
I'm glad you think so! Thanks for watching. :D
Nice video
Thanks very much! :)
so ive already finish your other video on raycast door *which is so helpful and amazing thank you!* and i just wanna ask can i use both the other raycast door in tandem with this one? like putting the raycast script and keyraycast script in the camera
You could do that but it wouldn't be particularly optimised, you could just create a script which is found in either case and check which type of door it is :)
@@SpeedTutor thanks you! btw do you have a video about game optimization or how to fully optimize your game?
Yes I do, search my channel for optimization! :) You'll find the big video.
I don't understand how to play the animation when the door is clicked with the key
Do I show that in this video?
@@SpeedTutor yeah, I watched both videos and i still dont understand how to link the animation to the door
@@SpeedTutor Never mind turns out i was missing a chunk of code from the KeyDoorController script thanks for the tutorial it all works now
i like your videos but ı wonder that is there a easier way to make door system
Of course, the possibilities are endless - This is just one example of how you could go about doing it! Thanks for checking it out though. :)
this guys makes the cleanest systems I have found.
Thanks Rob!
I believe I am having some issues with the door not opening and the UI not showing up. The key collects just fine and the cursor works great on the key and door.
Any errors?
Great tutorial! However, I have a problem. When I try to open or close the door after picking up the key, the animations play infinitely. For example, when i try to open the door DoorOpen animation plays endlessly. I checked the code and I am sure that the code only work once when I do that.
Did you turn off loop in the animation?
Fantastic tutorial! Everything I wanted & needed!
I had a question about the crosshair though - how would I go about making it an image like a small dot by default, then making that dot turn into a different image (like a keycard) when i'm looking at a door?
I think it'd look great with the code you set up with this tutorial (and it'd be perfect for the game i'm making!)
And thanks again for making this tutorial, it's fantastic :D
Thanks very much for saying so, in the method towards the bottom of the raycast where we change the colour of the crosshair, instead of changing the colour - Make this an image UI swap. You could use ".SetActive(true/false);" on a different UI in same place as the dot! :) I hope that helps.
Hi SpeedTutor, your tutorial is amazing so far. I got the crosshair, pick up key, door lock worked. Everything seems fine except opening the door animation. When I picked up the key and clicked the door. the game crashed saying
NullReferenceException: Object reference not set to an instance of an object
KeySystem.Key.KeyDoorController.PlayAnimation()
Do you have the correct animation component on your door?
@@SpeedTutor Nvm, fixed it. turns out it was public void Awake. I wrote "awake" instead of Awake. I can't believe that one letter was the cause of the crash. crazyyy. I wish Unity could have point out where the problem was instead of having me spending many hours looking for it. Anyways, thanks for the awesome tutorial!
I know the feeling! This is why you always have to go through error messages step by step. Look at what it's pointing to, and even what line might be pointing to another. It's a game of cat and mouse, most of the time! Good work though :)
@@SpeedTutor Unity was pointing the error at the key door script at line 53 which is the PlayAnimation part. So I thought it has something to do with the animator component like I was missing something xD. But yeah, I should have double-checked the script. Anyways, it's a good learning lesson haha. Thanks again!
I followed two of your door tutorial. The one with and without key. Both worked perfectly but the crosshair color for door with key is not changing and crosshair for door without key works fine. It's not really going to drag the game down because the scripts is all good but I would like to know the reason behind this. Any possible reason? I use the same crosshair for both door btw.
I'm not sure, maybe you're missing a tag?
I know this is late, but in case other people have the same issue:
I fixed this problem by making a separate tag for the interactableTag for the door that uses the key.
For example, instead of: private string interactableTag = "InteractiveObject";
For the key door I used: private string interactableTag = "InteractiveKeyObj";
Hope this helps!
how do i lock the door after? is there a way opposite this
NullReferenceException: Object reference not set to an instance of an object
KeySystem.keyDoorController.PlayAnimation () (at Assets/Scripts/Dont work/keyDoorController.cs:38)
KeySystem.keyItemController.ObjectInteraction () (at Assets/Scripts/Dont work/keyItemController.cs:28)
KeySystem.keyRayCast.Update () (at Assets/Scripts/Dont work/keyRayCast.cs:44)
I'm not sure what lines these are?
@@SpeedTutor lines 38, 28, and 44 according to the error
Hi, can you show how exactly to setup door animation that you wrote in scripts with bool etc...?
I have a tutorial, it's in the description too: ua-cam.com/video/gj9Eq3WJLJo/v-deo.html&
I hope that helps! :)
Thanks for the tutorial! but there's a problem to me when I try to add more key.
I don't know I missed something or not. But when I added another key, I can pick up that key.
but when I tried to open the door, I got a NullReferenceException in KeyItemController.ObjectInteraction.
I check the error line and it's a "doorObject.PlayAnimation".
I don't know what to do. I change the type of door and key and already have the animation.
Does your door object have an animation component?
@@SpeedTutor Yes, I've already put it. I tried to create a new one and copy the old one but they still have same problem when I change to other door that isn't a first door. ;w;
I dont know what I'm doing wrong.
Whenever I click the door w/ or w/o the key, I get this same error.
NullReferenceException: Object reference not set to an instance of an object
KeySystem.KeyItemController.ObjectInteraction () (at Assets/My Assets/My Scripts/KeyItemController.cs:28)
KeySystem.KeyRaycast.Update () (at Assets/My Assets/My Scripts/KeyRaycast.cs:43)
Hi I am continuously trying this tutorial for 3 days now😂 I was trying to replace the mouse click with just pressing ’D’. I am pretty sure I have followed everything correctly! I don’t know why it’s not working. Like literally anything, can’t pick up the key, no UI, can’t open the door..is there any way I could share the scripts with you so you can take a look? I would really appreciate that. Thanks!
You can join my Discord and post the script in there, are you sure you're using the correct tags? Always best to add Debug.Log lines into your code to see if each part is working. :)
the 2 namespaces tool and image weren't found is the image one because i already have a script with one of your other ray casted doors? and idk what to do about the tool part?
I'm not sure what you mean?
You lost me at first on the bit wise but it's like Assembly language were you rotate left out shift left or right?
Pretty much, it's just comparing the two layers. I don't really know why but that's the way to do it! Haha.
I don't normally ask about things through comments and I know this comment is late on this video as well, but I am genuinely confused about what I'm doing wrong. I've created more keys and doors, have set up the script onto each thing, but when I collect one key, it allows me to open all doors. Not simultaneously, but individually without having to collect the actual key for that specific door.
Did you set a boolean on each particular door and have it check if you have a particular key? :o
@@SpeedTutor I believe so, I may have done something wrong with it, but I'm not really sure. I just know that the doors work and the keys can be collected, but for some reason, it doesn't matter which key is collected as it opens all the doors without having that doors specific key. I feel like I've messed up somewhere with the keys or something. By chance it is the booleans, which script would I be checking for the booleans for each door?
@@bmpproductions did you find the solutions?
@@MatrixCreator-01 Unfortunately, not in the way I had hoped. The only thing that worked for me was doing it in an annoying and more difficult way by making a separate script for every door. Although, I don't really recommend doing that because it really isn't very efficient.
@@bmpproductions somehow I found a easy or you can say shortcut
Your tutorial is very good. But now I have some questions, cuz I can't interact with the key(crosshair wont change color and key cannot be picked),but the door is normal(when crosshair is on it, it turned red and can show doorlocked UI),any possible reason?
Do this system use tags and layers? I can't recall? If so, you might want to make sure nothing is occluding the key? Big enough box collider? Did it work before?
Hey thank you for the tutorial I had a question I am using Dungeon Builder(UnityAsset) to Create random worlds I made the door a prefab however the keyInventory EmptyObject gets removed for each door is there a way to add into the script to look for the keyInventory after each door is created?
Would finding the Gameobject and compoennt on start work?
I can't select type from "keyItemcontroller". I can not see the options. what can I do?
Is there any errors?
@@SpeedTutor it is not say error.
If you have 20 different keys, you suggest for each write if else statement? This code doesnt look OOP
This is just one example of how you could do it! :)
@@SpeedTutor but it's not working one key open all doors
How to use the pickUp key code to pickUp a flashlight and to make that flashlight work with a FPS controller?
I have a Unity asset on my store page just for that :)
Hi ! very nice and useful tutorial. However I use Mirror for network multiplayer and it doesn't seem to work for me, what can I do? Do i have to replace Monobehavior by NetworkBehavior ?
Sorry, that's not something I'm sure about at all.
Can't add script component "keyitemcontroller" because the script class cannot be found i have the same problem with door and raycast. And its says that there is no monobehavior scripts in the files
Is the script name the same as the class name?
@@SpeedTutor I feel a bit embarrassed to ask, but where can I find the class name?
That's alright, don't worry. If you open up one of your script at the very top it will have something like: public class "NAMEOFCLASS" : MonoBehaviour - Just change the name of the class there :)
@@SpeedTutor it is the same and still says no monobehavior scripts in the file, or thier names do not match the file name
Thanks a lot for this tutorial, one question : How can I add a lock sound when the player touches the door when he doest have the key? I tried figure it out myself but I have no idea where to place the audioplay
You could do it when we check for the interaction, if you don't have a specific key play the audio. You might need to make a check if one doesn't already exist! :)
@@SpeedTutor Whats the name of the asset pack?
I'm doing something wrong trying to add more keys and doors. When I try it, if I have any key at all, I'm able to open any door.
Am I missing something?
have you solve it?
Same problem here :(
Nice tutorial, but I ran into a problem.
If I first interact with the key, the game object disappears as it should, but I can't interact with the door.
But if I first interact with the door, it says "Door locked", and if I then interact with the key, it also says "Door locked".
I've assigned the red key to "red key", and the door to "red door", but for some reason, they're treated the same.
Are you sure the script is looking for the correct tags in this case?
@@SpeedTutor Yup, the Layer Mask Interact on the Camera's Key Raycast Script is on "Interact".
The door objects tag is "InteractiveObject", and layer on "Interact", and the red key object is tagged "InteractiveObject" as well as on the "Interact" layer.
I got it working. I had ignored all the code on the crosshair section, because I didn't want a crosshair ingame, and it caused the issue. Works now, but my method is basically having an invisible crosshair there, in order for it to function. Would this be advisable, or is there another better way to do it?
Is the KeyRaycast script the exact same as the DoorRaycast you made a while back?
It's similar, if not the same with maybe a couple of lines changed! :)
Hello. Did you remove Door Interaction Kit? Asset Store shows it as Deprecated.
It's now part of my Patreon because I'm trying to raise money for the channel! :) Thanks for taking an interest!
Hey, I have a problem where i cant drag my game object into the My Door part of the script. Im using a regular game object and not a model. Any fix?
Is it because it's missing the particular component it's looking for in the inspector slot? :)
@@SpeedTutor i got it, thanks for the reply and the tutorial! Super helpful for my college project 😭
Can you pls help me? Im getting error with a StartCorountine(PauseDoorInteraction()); and StartCorountine(ShowDoorLocked());
What's the error?
@@SpeedTutor KeyDoorController.cs(45, 36) CS1503 Argument1: cannot convert from 'System.Collections.IEnumerable' to 'string'
I fixed it, i write numerable not numerator
@@SpeedTutor I got other problem, the key pick-up, but the door wont open when i click on it. I tried to remake this two times and nothing.
@@SpeedTutor nvm i fixed it. Ty for tutorial
Hey umm, so I cant add the script onto the key, its telling me "Can't add script component 'KeyItemController' because the script class cannot be found. Make sure that there are no compile errors and that the file name and class name match." what does this mean? and how can i fix it? I'm quite new to coding ^^"
Is your script the same name as your class name?
So Im trying to use this system with a lot of keys and a lot of doors. So I added more else if statements with the names of the other keys but I cant open all doors with all keys still. Do you know a solution for this or know someone that does?
same problem did you find the solution?
Works great... but one key opens all doors.
It doesn't do that for me, are you sure you're using different instances?
@@SpeedTutor I made the different keys the way you said in the video and changed the key tag for the other key I made, but picking up any key causes all key doors to open. Is there anything that I have to do for the other door/doors to let only one key work for each door/doors?
When it didn't work I added classes to each key and even added different door classes and tags. I tried different things and none of them worked, one key still opened all doors.
@@SpeedTutor I'm pretty sure I'm using different instances.
I Figured it out. Though I had to make a different door controller script for each door and add new doors as well for those who are curious.
Great tutorial! i just had 1 problem. i have a sliding door with two panels and when i have the key and try to open it, nothing happens
So the animation doesn't play? They aren't static are they?
@@SpeedTutor I got it figured out :D Thanks for the tutorial.
How did you fix it?
@@sharkfinn1840 HOW TELL ME PLS
Brother i have a Problem, the script error says that CrosshairChange, Crosshair, and doOnce is not there. I made this what you did. Can you help me pls i not know what is wrong.
I'm not sure without seeing your script?
@@SpeedTutor This is the Script
I dont know whats false:(
:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace KeySystem
{
public class KeyRaycast : MonoBehaviour
{
[SerializeField] private int raylength = 5;
[SerializeField] private LayerMask layerMaskInteract;
[SerializeField] private string excluseLayerName = null;
private KeyItemController raycastedObject;
[SerializeField] private KeyCode openDoorKey = KeyCode.Mouse0;
[SerializeField] private Image crosshair = null;
private bool isCrosshairActive;
private bool doOnce;
private string interactableTag = "InteractiveObject";
private void Update()
{
RaycastHit hit;
Vector3 fwd = transform.TransformDirection(Vector3.forward);
int mask = 1
Could i do this but in VR or dose that requier alot more coding?
It's perfectly possible in VR! :)
fixed it
Great to hear it, how did you fix it?
@@SpeedTutor I added bools to the door controller script for each door then made the open door function only trigger if you had the right key and the right bool was ticked
in my scenario i have multiple doors and each door has its specific key can you please help me to solve the problem
It should work for that :)
@@SpeedTutor This is not a good way to help people, just saying "Yeah it should work" doesn't help.
@@doriantermini if the question isnt clear and almost written as if its saying "hey look i did this" and just ask for help *without stating what the problem is* then what else could he do?
What should the animator controller be?
I'm not sure what you're asking me? :o
Have you done one where it's a password instead of a key?? If not will you do one?
I have an asset on the Unity store which does this! :)
i have a question my unity crashes when i pick up the red key and look at the door do you know what causes this?
Do you have errors? Is this crashing in the editor?
@@SpeedTutor nope its crashing while i test it
@@SpeedTutor can i get your email or something i can send a video tomorrow? :)
Sure you can get my email from the "About" page on my channel, through my website or even message me on Discord :)
@@SpeedTutor okay
Hola Gamers!
Having a wee problemo here. The key object nor the door object are doing anything. Crosshair doesn't change colour and the text won't show on screen. There's no error messages or issues in the code from what I've seen. If anyone has any suggestions or solutions I'll give you a virtual high five! Version: Unity 2021.3.9f1
That's really hard to diagnose, I can't remember if this code relies on tags?
@@SpeedTutor Thanks for responding! It does rely on tags 'InteractiveObject' for the tag and 'Interact' for the layer
is this a update for the door asset ?
No, no - This is already included in the door asset but it's showing everyone how to make it, if they don't have the pack! :)
I get (12,60): error CS1519: Invalid token '=' in class, struct, or interface member declaration
This seems to be referring to the key item controller script. I'm new to this so can anyone help? Pleeeaseeeeeee
What is on line 12?
@@SpeedTutor thanks for the reply.
Full code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace KeySystem
{
public class KeyItemController : MonoBehaviour
{
[SerializeField] private bool houseDoor = false;
[SerializeField] private bool BlackKey = false;
[SerializeField] private KeyInventory_keyInventory = null;
private KeyDoorController doorObject;
private void Start()
{
if (houseDoor)
{
doorObject = GetComponent();
}
}
public void ObjectInteraction()
{
if (houseDoor)
{
doorObject.PlayAnimation();
}
else if (BlackKey)
{
_KeyInventory.hasBlackKey = true;
gameObject.SetActive(false);
}
}
}
}
Line 12:
[SerializeField] private KeyInventory_keyInventory = null;
Is that because you don't have a space between "KeyInventory" and "_keyInventory"?
Also "_keyInventory" - This is the variable
Is spelt different to:
_KeyInventory.hasBlackKey = true; - This is what you use in the code.
@@SpeedTutor hi, I done that and I'm now getting three further errors with the raycast.
(17,35) error CS0246: The type or namespace name 'Image' could not be found (are you missing a using directive or assembly reference?)
(17,10) error CS0246: The type or namespace name [SerializedFieldAttribute] could not be found (are you missing a using directive or assembly reference?)
(17,10) error CS0246: The type or namespace name [SerializedField] could not be found (are you missing a using directive or assembly reference?)
No matter what I try I get the same error. "The script don't inherit a native class that can manage a script".
Is the class name the same as the script name?
@@SpeedTutor They all have "public class Example : MonoBehaviour " with their names being the same as the script names
You want to give each of your classes a different name
@@SpeedTutor
KeyRaycast - "public class KeyRaycast : MonoBehaviour"
KeyInventory - "public class KeyInventory : MonoBehaviour"
KeyDoorController - "public class KeyDoorController : MonoBehaviour "
KeyItemController - "public class KeyItemController : MonoBehaviour"
I think these are the classes you're talking about?
@@SpeedTutor I don't know how :(
Do it work same as in 2d game
It could if you changed it slightly.
animation doesn't work :(
Your door isn't static, is it?
@@SpeedTutor no
İs this works on mobile ?
It could work on mobile, I've never tested it but I don't see why not! :)
it works, but only for one key it seems. which is a bit disappointing. i don't understand why he didn't just show how to add additional keys and doors, if it indeed works.
It indeed does work for multiple keys and doors, you just need to add them yourself as additional variables. :)
@@SpeedTutor yea, i understood as much, although one key would open all doors for me. I'd just suggest showing how to implement at least one extra key, so that there's an example to go after.
@@SpeedTutor you know, just saying "hey, yea, this works" doesn't really help those who have problems expanding the system.
Hey I had the same problem how did you solve it?@@dexterdextrow7248
Anyone have trouble getting the door to close?
In what way? :o
@@SpeedTutor It was a syntax error in the script I didn't notice. I had tired eyes. All good now, great tutorial, very helpful!
Fantastic! Good work! :)
Soooo zoomed out omg
Sorry about that, it's always pretty zoomed in on my screen but I'll make it bigger for next time :)
quit at Keyinventory script... need a cube tutorial not a pre set up game
I do have several other tutorials showing you how to add doors and other such things! :)
Not for beginners
I believe in you! You can do it!
Unity returns error CS1002 on two lines with WaitForSeconds() at KeyDoorController.cs. It expects a semicolon even if it's typed already. I use Unity 2020.3.33f1.
I imagine you have a grammar or syntax issue somewhere close to that line. Maybe above or below. :)
I have checked the syntax few hours ago, and realized that I typed "now" instead of "new." Thank you! 😊 I think I need more rest.
Haha, it easily be done. Good job on fixing it! :)