What do you want to achieve? Keep it simple and clear!
To fix this error, i havent got any working solutions yet
What is the issue? Include screenshots / videos if possible!
Infinite Yield Possible On player.Backpack:WaitForChild(“Key1”)
Why/How It Happened
It happens when equipped another tool it wont work ,maybe since the first tool deequipped it is inserted into game.Players.Player.Backpack
instead of Staying In The Character Model
but i still couldnt figure out the solution.
Code:
local prox = script.Parent.ProximityPrompt
local lock = script.Parent.Parent.Lock1
local str = script.Parent.Parent.Value
local door = script.Parent.Parent.door
prox.Triggered:Connect(function(player)
wait(1)
player.Backpack:WaitForChild("Key1"):Destroy()
str.Value += 1
prox.Enabled = false
if str.Value == 2 then
str:Destroy()
door.Transparency = 1
door.CanCollide = false
end
end)
Check if the Tool is in the Player’s Character, then check if the Tool is in the Players Backpack, use :FindFirstChild() when it comes to this, it wont yield like with :WaitForChild(), however you have to make sure the object exist using an if statement.
For Example:
local obj = example:FindFirstChild("Key1") -- looks for object
if obj then -- if object found
obj:Destroy() -- destroy object
end
For this you would have to add an edge case for the character as well. Here’s an example of how you could do it
-- Previous Code
-- player.Backpack:WaitForChild("Key1"):Destroy()
key = nil
if player.Backpack:FindFirstChild("Key1") then
key = player.Backpack:FindFirstChild("Key1")
elseif player.Character:FindFirstChild("Key1") then
key = player.Character:FindFirstChild("Key1")
end
if key ~= nil then
-- rest of your code
end
This works because it is taking into account that the tool may be activated inside the character. But additionally, it also takes into account that they may not have the key.