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

How Do I Know The Last Key Pressed?

I'm trying to see if I can identify the previous key pressed. I want to know so that I can make sure the last gun I used is nil and that I can use the new gun I am currently using.

local CurrentGun
local PrevGun = ?

InputService.InputBegan:connect(function(key, gpe)
	if key.KeyCode == Enum.KeyCode.One  or key.KeyCode == Enum.KeyCode.KeypadOne and not gpe then
		local PP = PPart:Clone()
		PP.Parent = Character
		CurrentGun = PP
	elseif key.KeyCode == Enum.KeyCode.Two or key.KeyCode == Enum.KeyCode.KeypadTwo and not gpe then
		local SP = SPart:Clone()
		SP.Parent = Character
		CurrentGun = SP
	elseif key.KeyCode == Enum.KeyCode.Three or key.KeyCode == Enum.KeyCode.KeypadThree then
		local BP = BPart:Clone()
		BP.Parent = Character
		CurrentGun = BP
	end
end)

1 answer

✓ Accepted answer

You have the right idea with the variables, you just need to implement the prevGun. It's not hard.

--using fake stuff for simplicity's sake
currentGun = nil
prevGun = nil

onInput:connect(function(key)
	if key == 1 then
		newGun = PPart:Clone()
		prevGun = currentGun
		currentGun = newGun
	end
end)

See how that works? When a new gun is equpped, currentGun is actually the previous gun until we reset its value. That means we can use currentGun to set prevGun correctly, as long as we do this before we update it.

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