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

Help with UserInputService, Enum.KeyCode.LeftShift?

This Local Script is in StarterGui and it only works a few times. So when my minigame starts and tps players, I am still able to jump when pressing but when the minigames fires ':LoadCharacter()', it does not work after that.

local UserInputService = game:GetService('UserInputService')
local Player = game.Players.LocalPlayer
local Character = game.Workspace:WaitForChild(Player.Name)

UserInputService.InputBegan:connect(function(Input)
	local KeyCode = Input.KeyCode
	if KeyCode == Enum.KeyCode.LeftShift then
		print'a'
		Character.Humanoid.Jump = true
	end
end)

1 comment

0

It's probably due to line 3 where you wait for the player to load I could be wrong though..

1 answer

Player's character

You really shouldn't attempt getting the character by indexing the workspace for the player's name. You should access the player's character by directly indexing the local player, which will get that specific user's character - not whatever the workspace gives you.

Naive approach

The naive approach to handling this would just simply be trying to get the character from the player, without waiting for it to load. Most of the time, the local script loads before the character does. Meaning you need some way to wait for the character to be added to the player, before the script continues.

Lucky for us, there's an event just for this purpose called CharacterAdded! This is how you'd get the character from the player:

-- Players & Player
local players = game:GetService("Players")
local player = players.LocalPlayer

-- Character from the local player (most likely will not be loaded in)
local character = player.Character

Now here's an example implementing the same method of getting the character, but mixed with an or statement that tells us to wait for the character to be added, then return the character. Here's an example:

local players = game:GetService("Players")
local player = players.LocalPlayer

-- If 'player.Character' returns nil, it will wait for the character to be added, the continue.
local character = player.Character or player.CharacterAdded:wait()

That is how you should always handle getting the character in a local script. As far as your UserInputService section goes, everything looks fine. Though, I do have a UserInputService module interface that makes working with UIS a lot easier to use if you're interested. You can find it here. Hope this helped, let me know if you have any questions!

4 comments

0

Still doing the same things. ;(

0

I tested it in studio, everything seems to work fine for me.

0

Weird...

0

Create a blank project just in case

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