✓ Accepted answer
Your Problem
You're cloning the part on line 3, this is outside of the KeyDown event.. therefore making it so the part only clones once, rather than everytime you press the key.
Also, on line 8, you're trying to make an Instance type of 'Rocket'. This instance type does not exist! You have to clone a premade rocket.. which you did on the beginning!
How To Fix
Move the cloning inside the KeyDown event. This way, the part will clone whenever you press said key(:
Further Efficiency Changes
- Make The Script A LocalScript!!
By making this code a localscript, you can access the player by indexing LocalPlayer from Players like game.Players.LocalPlayer. Also, you cannot get the mouse of the client without a localscript
- Instead of using the
KeyDown Event, use the InputBegan Event of UserInputService
The InputBegan Event can detect any user input.. meaning virtually any key on the keyboard.
Code
local Tool = script.Parent
local Bullet = Tool:FindFirstChild("Part")
local plr = game.Players.LocalPlayer
local uis = game:GetService('UserInputService')
function Input(i)
if i.KeyCode == Enum.KeyCode.E then
local Rocket = Bullet:Clone()
Rocket.Parent = workspace
Rocket.Position = plr.Character.Torso.Position
end
end
function onSelected()
uis.InputBegan:connect(Input)
end
script.Parent.Selected:connect(onSelected)
If you want to make the code look cleaner.. use Anonymous functions!
local Tool = script.Parent
local Bullet = Tool.FindFirstChild("Part")
local plr = game.Players.LocalPlayer
local uis = game:GetService('UserInputService')
script.Parent.Selected:connect(function()
uis.InputBegan:connect(function(i)
if i.KeyCode == Enum.KeyCode.E then
local Rocket = Bullet:Clone()
Rocket.Parent = workspace
Rocket.Position = plr.Character.Torso.Position
end
end)
end)
5 comments
I Agree, user input service is the best.
c:
I've only just had time to test this script, and it seems that it doesn't work. I made sure to use a LocalScript too. I've even tried just taking my original code and then putting the clone part into the function, but that didn't work either. My part that is being used as the rocket also has a mesh in it, does this affect the code at all?
Also, I would like to say thank you for the detailed explanation
I fixed an error on line 2 I didn't catch from yuor code.. "Tool.FindFirstChild('Bullet')" '.' should be ':'