Hello I am making a custom gun script and right now I am working on ViewModel, everything works right until i wanted to Kill my character, according to my script it should Destroy the ViewModel but it dosen’t even call “Died()” event but second time I die everything works right, any ideas where is the problem?
local localplr = game.Players.LocalPlayer
local UserInput = game:GetService("UserInputService")
local character = localplr.Character or localplr.CharacterAdded:Wait()
local head = character:WaitForChild("Head")
local Events = game.ReplicatedStorage.NewEvents
local shootEvent = Events.Shoot
local EquipViewModelEvent = Events.EquipViewModel
UserInput.InputBegan:Connect(function(input, gameProcessEvent)
if not gameProcessEvent and input.UserInputType == Enum.UserInputType.MouseButton1 then
local mouse = localplr:GetMouse()
local rayOrigin = head.Position
local rayDirection = (mouse.Hit.Position - rayOrigin).unit * 80000
local raycastParams = RaycastParams.new()
raycastParams.FilterDescendantsInstances = {character}
raycastParams.IgnoreWater = true
local raycastResult = workspace:Raycast(rayOrigin, rayDirection, raycastParams)
if raycastResult then
local partHit = raycastResult.Instance
local distance = (rayOrigin-raycastResult.Position).magnitude
local position = raycastResult.Position
shootEvent:FireServer(partHit, position, distance)
end
end
end)
EquipViewModelEvent.OnClientEvent:Connect(function(ViewModel: Model)
local Camera = workspace.CurrentCamera
local loop
localplr.CharacterAdded:Connect(function(character)
local humanoid = character:WaitForChild("Humanoid")
humanoid.Died:Connect(function()
print("dead xD")
if loop then
loop:Disconnect()
ViewModel:Destroy()
end
end)
end)
loop = game:GetService("RunService").RenderStepped:Connect(function()
if localplr.Character and localplr.Character:FindFirstChild("Humanoid") then
ViewModel:PivotTo(Camera.CFrame)
end
end)
end)