im trying to make a flashlight system for my game
The issue is this error
Ive looked throughout the dev forum but no solutions are working for me
local uis = game:GetService("UserInputService")
local clonelight = game.ReplicatedStorage.SpotLight:Clone()
local ison = false
local db = 0.5
game.Players.PlayerAdded:Connect(function(plr)
clonelight.Parent = plr.Character.Head
local light = plr.Character.Head:FindFirstChild("SpotLight")
uis.InputBegan:Connect(function(key)
if key.KeyCode == Enum.KeyCode.F then
if ison == false then
ison = true
light.Enabled = true
wait(db)
elseif ison == true then
ison = false
light.Enabled = false
wait(db)
end
end
end)
end)
You have to wait until the character appears you are doing these action the moment the player is added and you should also wait for the character to be added
local uis = game:GetService("UserInputService")
local clonelight = game.ReplicatedStorage.SpotLight:Clone()
local ison = false
local db = 0.5
game.Players.PlayerAdded:Connect(function(plr)
plr.CharacterAdded:Connect(function(char)
local head = plr.Character:WaitForChild("Head")
clonelight.Parent = head
local light = head:FindFirstChild("SpotLight")
uis.InputBegan:Connect(function(key)
if key.KeyCode == Enum.KeyCode.F then
if ison == false then
ison = true
light.Enabled = true
wait(db)
elseif ison == true then
ison = false
light.Enabled = false
wait(db)
end
end
end)
end)
end)
local character = plr.Character or plr.CharacterAdded:Wait()
local light = character.Head:FindFirstChild("SpotLight")
This will attempt to set a character variable to the player’s character. If the character doesn’t exist yet (hasn’t loaded), it will wait until it has loaded and then set the variable to the character.
Edit: Nevermind, the solution above is better, as the character would be updated whenever the player respawns.