I’m working on a gun and this script isn’t creating a beam like I want it to.
-- Variables
local player = game.Players.LocalPlayer
local tool = script.Parent
local shootPart = tool.AKM.shootPart
local mouse = player:GetMouse()
local uiService = game:GetService("UserInputService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local equipped = false
-- Firing Functions
local function semiFire()
local ray = Ray.new(shootPart.CFrame.p, (mouse.Hit.p - shootPart.CFrame.p).unit * 300)
local part, position = workspace:FindPartOnRay(ray, player.Character, false, true)
local beam = Instance.new("Part", workspace)
beam.BrickColor = BrickColor.new("Really red")
beam.FormFactor = "Custom"
beam.Material = "Neon"
beam.Transparency = 0.5
beam.Anchored = true
beam.Locked = true
beam.CanCollide = false
local distance = (shootPart.CFrame.p - position).magnitude
beam.Size = Vector3.new(0.1, 0.1, distance)
beam.CFrame = CFrame.new(shootPart.CFrame.p, position) * CFrame.new(0, 0, -distance / 2)
game:GetService("Debris"):AddItem(beam, 0.1)
if part then
local humanoid = part.Parent:FindFirstChild("Humanoid")
if not humanoid then
humanoid = part.Parent.Parent:FindFirstChild("Humanoid")
end
if humanoid then
local akmEvent = ReplicatedStorage.Guns.AKM:WaitForChild("akmEvent")
akmEvent:FireServer(part, humanoid)
end
end
end
--Equip / Unequip
tool.Equipped:Connect(function(mouse)
equipped = true
end)
tool.Unequipped:Connect(function(mouse)
equipped = false
end)
-- Click
uiService.InputBegan:Connect(function(input)
if equipped == true then
if input.UserInputType == Enum.UserInputType.MouseButton1 then
semiFire()
print("shoot@!!1!")
end
end
end)
uiService.InputEnded:Connect(function(input)
if equipped == true then
if input.UserInputType == Enum.UserInputType.MouseButton1 then
print("stop shoot :(()()()")
end
end
end)
Are you getting any errors in the output? I recreated a gun with your script and got an error on line 5 (AKM is not a valid member of Tool). Changing line 5 to this fixed it and the beam fired with no issues.
local AKM = tool:WaitForChild("AKM")
local shootPart = AKM:WaitForChild("shootPart")
The error is caused because the script runs before the game has a cheance to create the gun parts, hence they dont exist when you define them and cause the error. WaitForChild solves this by waiting until the instance exists before proceeding.
I read over the code and it seems okay. I could definitely be missing something. Could you please put some print statements in to figure out where the code stops doing what you expect it to?
Is shootPart welded properly? If you want to attach/DM a repro file of the tool i can take a look at it. The code is good, just looks like its an issue with the gun model or possibly the server script. Here is the file of the test gun, the beam fires with no issue for me. TestGun.rbxm (4.7 KB)