Turning on and off a Lightsaber

Hello there! I’m working on a lightsaber game and recently I’ve hit a problem. I don’t really know how to script. I tried and ended up with this script for a turning on and off a lightsaber that, well, doesn’t work.
Basically when I try to turn on the lightsaber, it doesn’t do anything. I do not know whether it’s the script type, or my actual script.
The script type is a normal script, not a local script or module script.
The Script:

game.Players.LocalPlayer:GetMouse().KeyDown:Connect(function(key)
	if key == "q" then
		script.Parent.Handle.CrystalPart.Transparency = 0.15
		script.Parent.Handle.LightPart.Transparency = 0.15
		if script.Parent.Handle.CrystalPart.Transparency == 0.15 then
			script.Parent.Handle.CrystalPart.Transparency = 1
		if script.Parent.Handle.LightPart.Transparency == 0.15 then
			script.Parent.Handle.LightPart.Transparency = 1
			end
		end
	end
end)
1 Like

Local events would need to be handled by a LocalScript. Also you should probably use UserInputService for this. Then if you want it to actually show up server-side, you’ll need to use a remote.

See also:

1 Like

It’s a local script now, but there’s one problem. Now it turns on, but it won’t turn off, how would I fix this?

My current code is the one at the top.

I found one with the studio toolbox item #(6028291724) called:
WORKS Lightsaber!!! By artem4ikKO
It uses the Q key and is doing just what you’re looking for.

Have fun!

As much as I appreciate this, I don’t want to use the toolbox, as I am challenging myself here. Thanks anyway!

You may want to take a look at it before you say that … :heart_eyes:
Learning from a working example is the best way to learn how to program.

I guess it is, I think I’ll look at it and see how it works.

Here’s how you’d go about it (though you should use remotes instead of changing it via the LocalScript):

local userInputService = game:GetService('UserInputService')
local players = game:GetService('Players')
local localPlayer = players.LocalPlayer

local handle = script.Parent:WaitForChild('Handle')
local crystalPart = handle:WaitForChild('CrystalPart')
local lightPart = handle:WaitForChild('LightPart')

local active
userInputService.InputBegan:Connect(function(key,process)
	if not process then
		if key.KeyCode == Enum.KeyCode.Q then
			active = not active
			if active then
				crystalPart.Transparency = .15
				lightPart.Transparency = .15
			else
				crystalPart.Transparency = 1
				lightPart.Transparency = 1
			end
		end
	end
end)

This works! I’m going to start studying the code to see how it works so I can make this type of stuff myself in the future.
Thank you, for two things:
Making this work
Helping me learn to script better.

1 Like