This script works great when you are using onTouched, but unfortunately I can't figure out how to make this work with onClicked. Could you please explain to me why this does not work with onClicked? I haven't been getting any errors so I'm not sure what to tackle next.
My script:
------------------------------------ local modelname="teleporter1b" ------------------------------------ function onClicked(part) if part.Parent ~= nil then local h = part.Parent:findFirstChild("Humanoid") if h~=nil then local teleportfrom=script.Parent.Enabled.Value if teleportfrom~=0 then if h==humanoid then return end local teleportto=script.Parent.Parent:findFirstChild(modelname) if teleportto~=nil then local torso = h.Parent.Torso local location = {teleportto.Position} local i = 1 local x = location[i].x local y = location[i].y local z = location[i].z x = x + math.random(-1, 1) z = z + math.random(-1, 1) y = y + math.random(2, 3) local cf = torso.CFrame local lx = 0 local ly = y local lz = 0 script.Parent.Enabled.Value=0 teleportto.Enabled.Value=0 torso.CFrame = CFrame.new(Vector3.new(x,y,z), Vector3.new(lx,ly,lz)) wait(3) script.Parent.Enabled.Value=1 teleportto.Enabled.Value=1 else print("Could not find teleporter!") end end end end end script.Parent.ClickDetector.MouseClick:connect(onClicked)
Thank you!
MouseClick
event listeners have a sole parameter, playerWhoClicked
. Touched
event listeners' parameter, however, is the part which was touched.
The reason it isn't working is because currently part
in your script would be the Player who clicked the part. You can fix this problem pretty easily:
EDIT: Somehow, I mistakenly thought that part
would be the part touched, instead of the part which touched it. Instead, you should get the player's character:
------------------------------------ local modelname="teleporter1b" ------------------------------------ function onClicked(player) local char = player.Character; --// You can get the character just as easily, with some small changes to the function as seen below. local h = char:FindFirstChild("Humanoid") if h~=nil then local teleportfrom=script.Parent.Enabled.Value if teleportfrom~=0 then local teleportto=script.Parent.Parent:FindFirstChild(modelname) if teleportto~=nil then local torso = char.Torso local location = {teleportto.Position} local i = 1 local x = location[i].x local y = location[i].y local z = location[i].z x = x + math.random(-1, 1) z = z + math.random(-1, 1) y = y + math.random(2, 3) local cf = torso.CFrame local lx = 0 local ly = y local lz = 0 script.Parent.Enabled.Value=0 teleportto.Enabled.Value=0 torso.CFrame = CFrame.new(Vector3.new(x,y,z), Vector3.new(lx,ly,lz)) wait(3) script.Parent.Enabled.Value=1 teleportto.Enabled.Value=1 else print("Could not find teleporter!") end end end end script.Parent.ClickDetector.MouseClick:Connect(onClicked)
Also, though yours wasn't too bad, I still urge you to try to always practice correct indentation of blocks.
Hope this helped.