How to add lock and unlock door with a key

I’m pretty new to scripting for my own project.
To explain the topic further, I am currently making a door using Proximity, simple open and close as you press “E”.
Anyways, you know how in The Mimic, where they add these locked doors and that players need to find a key to unlock the door. I am struggling to figure out how to add a key connected to the door.

Script:

local frame = script.Parent:WaitForChild("DoorFrame")
local openSound = frame:WaitForChild("DoorOpen")
local closeSound = frame:WaitForChild("DoorClose")
local proximityprompt = frame:WaitForChild("ProximityPrompt")
local model = script.Parent
local frameClose = model:WaitForChild("DoorFrameClose")
local frameOpen = model:WaitForChild("DoorFrameOpen")
local tweenService = game:GetService("TweenService")

proximityprompt.Triggered:Connect(function()
	if 	proximityprompt.ActionText == "Close" then
		proximityprompt.ActionText = "Open"
		closeSound:Play()
		tweenService:Create(frame,TweenInfo.new(.35),{CFrame = frameClose.CFrame}):Play()
		else
		proximityprompt.ActionText = "Close"
		openSound:Play()
		tweenService:Create(frame,TweenInfo.new(.35),{CFrame = frameOpen.CFrame}):Play()
		end
	end)

The script above is the main script to the door! How do I add a “key” and make the door lock, so that you need the key to unlock the door.

Have you looked into the Dungeon Delve place shown in Implementing Proximity Prompts?

You basically need to check to see if whoever is clicking the proximityprompt.Triggered event has the key.
In the following line, put another if statement to check for the key, and if they have it then check for the if ...ActionText... = "Close"

I used the Search tool up top and found this post which shows how to check if a player is in a team, similar to checking if they have a key in their tools.

1 Like

Is the key a tool or is it just displayed on a gui once you’ve found it because if so, you could do…

When the player finds the key and “equips” it, you should give them an attribute:

player:SetAttribute("HasKey", true)

Then in the code you are presenting here, write this…

else
    if player:GetAttribute("HasKey", true) then
	    proximityprompt.ActionText = "Close"
        openSound:Play()
        tweenService:Create(frame,TweenInfo.new(.35),{CFrame = frameOpen.CFrame}):Play()
    end
end
end)

Also note that you can change “HasKey” to any name that you desire

LMK if there are any issues!

3 Likes

If I were to use this code, where would the desire position be? As I try to add the attribute: player:SetAttribute("HasKey", true)
It doesn’t work. It is probably where I am placing it.

I’m sorry if I am being confusing.

Do you have the code for when the player collects the key?

Oh! I figured out the problem now, thank you!

If you figured it out, please mark the comment as the Solution, to keep the site organized.

2 Likes