Make sound play when key press?

After some recent drama i decided to go back to my Czechoslovak train simulator, so far I’m scripting a locomotive and I’m trying to make it so that when i press a certain key (H or B) a different sound is played according to the key pressed respectively. Here is the script I am using.

local Vehicle = script.Parent.Parent.VehicleSeat

Vehicle.Touched:Connect(function(sit)
	
	local sound = Instance.new("Sound", game:GetService("ReplicatedStorage"))
	sound.Parent = game.Workspace:WaitForChild("363").Horn
	sound.Name = ("363Horn")
	sound.SoundId = "rbxassetid://12272587082"
	game:GetService("UserInputService").InputBegan:Connect(function(key)
		if key.KeyCode == "H" then
			sound:Play()
		end
	end)

	local sound2 = Instance.new("Sound", game:GetService("ReplicatedStorage"))
	sound2.Parent = game.Workspace:WaitForChild("363").Horn
	sound2.Name = ("363Whistle")
	sound2.SoundId = "rbxassetid://12272587025"
	game:GetService("UserInputService").InputBegan:Connect(function(key)
		if key.KeyCode == "H" then
			sound:Play()
		end
	end)
	
end)



The code is supposed to detect when the player sits on the VehicleSeat and when they do they are able to play either a horn or whistle if they press H or B and when they get off they cant do so (obviously)? So far it hasn’t been working and I don’t know what else to do

This script is put inside a MeshPart called Horn, in which the sounds come from

Any suggestions?

2 Likes

If you are running this script on the server side the UserInputService won’t work since it doesn’t replicate. I think a good way to do this would be replicating when the user input begins/ends with a RemoteEvent as shown in this post.

Edit : I think your question fits Scripting Support better than Platform Usage Support.

You would need to use a local script to check when you press a key and make it fire a remote event

you could check if the player is in a seat with something like:

if Humanoid.Sit == True then 
    --code
end
1 Like

you can just do:

if Humanoid.Sit then 

to check if false:

if not Humanoid.Sit then 

Hey im pretty sure it’s

if key.KeyCode == enum.keycode.H then

And you can always add some prints here and there to see if it works

cant i just use an ifelse statement for that?

I mean i know how to script the key pressing part its just that the only pain is trying to get the script to be able to detect if the player is sitting in a vehicleseat or not

Both Seat and VehicleSeat have a property called Occupant that stores the humanoid who is sitting on the seat, you can use it to check if the humanoid in question is seated on the specific seat.