What do i want to achieve?
I want to make a script that kills user’s like arsenal when you hit the backspace button
What is the issue?
The issue is Workspace.Part.User:3: attempt to index nil with ‘Character’
What solutions have you tried so far?
I tried looking for similar post like this but I could not find it.
The script
local UserInputService = game:GetService(“UserInputService”)
local player = game.Players.LocalPlayer
local char = player.Character or player.CharacterAdded
local Humanoid = char:WaitForChild(“Humanoid”)
UserInputService.InputBegan:connect(function(input, gameProcessedevent)
if input.KeyCode == Enum.KeyCode.Q then
wait(3)
Humanoid.Health = 0
end
end)
You want to kill the player from the server side, so the other players will see it.
First put a RemoteEvent named “PlayerReset” in game.ReplicatedStorage.
Then add these scripts:
LocalScript in game.StarterPlayer.StarterPlayerScripts:
local uis = game:GetService("UserInputService")
local event = game:GetService("ReplicatedStorage"):WaitForChild("PlayerReset")
uis.InputBegan:Connect(function(input, gpe)
if (input.KeyCode == Enum.KeyCode.Q and not gpe) then
event:FireServer()
end
end)
Regular Script in game.ServerScriptService:
local event = game:GetService("ReplicatedStorage").PlayerReset
event.OnServerEvent:Connect(function(player)
local humanoid = player.Character and player.Character:FindFirstChild("Humanoid")
if (humanoid) then
humanoid.Health = 0
end
end)
Covered by Post #2 but to make sure that there is a character, use CharacterAdded:Wait() so that the script will wait until a character has been found
Change input.KeyCode == Enum.KeyCode.Q to input.KeyCode == Enum.KeyCode.Backspace
To prevent players from dying just by chatting, check the gameProcessedEvent and check if it’s been activated, then you can return (Or end) the function early
I do also recommend using RemoteEvents so you can fire the event from the client to the server as @blokav mentioned before, that way you can handle the killing from the server
It’s a ternary expression that checks whether player.Character exists before searching it for the Humanoid. If either the humanoid or character is nil the variable would resolve to nil.