Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Why does this keydown script return output with "attempt to call a nil value"?

I put this code into a local script in Start Pack

Player = script.Parent.Parent
mouse = Player:GetMouse()

function onKeyDown(key)
	key = key:lower()
	if key == "z" then
		TestHouse = game.Lighting.House:clone()
		TestHouse.parent = game.Workspace
	end
end

mouse.KeyDown:connect(PressedZ)

Its supposed to detect that I pressed Z and then clone game.lighting.House But when I press Z the output returns with "attempt to call a nil value" in red.

Any thoughts as to why this doesn't work?

2 comments

0

Are you sure all your paths are correct? And instead of using Player = script.Parent.Parent, use Player = game.Players.LocalPlayer to ensure you get the player.

0

Don't use KeyDown, don't use Lighting as storage, and don't define the player by spamming .Parent.Parent. All of these things make your code ugly.

1 answer

✓ Accepted answer

At line 12, the function PressedZ isn't written beforehand in the script. Try replacing that with "mouse.KeyDown:connect(onKeyDown)"

Also, I think the nil value is from line 8, where you try to set the parent of the house to Workspace. You put in "parent", when the property is named Parent. (CaSE SEnSITiVe!)

Player = game:GetService('Players').LocalPlayer
mouse = Player:GetMouse()

function onKeyDown(key)
    key = key:lower()
    if key == "z" then
        TestHouse = game.Lighting.House:clone()
        TestHouse.Parent = game.Workspace
    end
end

mouse.KeyDown:connect(onKeyDown)

(Side note, KeyDown is now deprecated. UserInputService is a better choice.)

Don't forget to accept my answer if this helps!

This discussion is preserved as it was. New answers, comments, and votes are closed.