Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Why is my teleporting script not functional?

Alright so I am helping work on a game, and for a powerup when a certain brick is hit a player will teleport to a random player on the opposite team, I made a script that should work, but doesn't No errors, just does not work.

script.Parent.Touched:connect(function(plr)
	
function switched()
	for _,v in pairs(game.Players:GetChildren()) do
		if v.Name == hit.Parent.Name then
			
		local pos = v.Character.Position
		for _,c in pairs(game.Players:GetChildren()) do
			if c.TeamColor == BrickColor.new("Bright blue") then
				local pos2 = c.Character.Position
				
				local pos = pos2 and pos2 == pos
			end
		end
		end
	end
end	
	switched()
end)

Any and all help is appreciated

1 answer

✓ Accepted answer

Ok, so that has some errors. First of all, why did you make a function inside of another function? I mean, if you make something that's going to be used multiple times within the .Touched, it would be useful to make the function, but since you only use that function once, and that's the only thing you use in the .Touched, there is no reason to make another function.

part = script.Parent

part.Touched:connect(function(hit) --hit equals what hits the part
	local player = game.Players:GetPlayerFromCharacter(hit.Parent) --gets the player object from a char, it returns nil if hit.Parent is not a Character
	if player then --if it's not nil
		local players = game.Players:GetPlayers() --like GetChildren(), but only returns player objects, just in case something else ends up in game.Players
		local num = math.random(1,#players)
		while players[num]==player do --make sure you don't have the same player that touched
			num = math.random(1,#players)
		end
		local otherPlayer = players[num] --gets the other player
		
		torso1 = player.Character.Torso
		torso2 = otherPlayer.Character.Torso
		torso1.CFrame = torso2.CFrame --you change the cframe of the Torso to teleport a player
		
	end
end)

If you find anything wrong with this, please tell me in a comment.

And here's an example of when it would be a great idea to make a function inside of another function.

function thing()
	local function randParts(num)
		local parts = {}
		local childs = game.Workspace:GetChildren()
		for q=1,#childs do
			if childs[q]:IsA("BasePart") then
				table.insert(parts,#parts+1,childs[q])
				if #parts ==num then
					break
				end
			end
		end
		return parts
	end
-- I use randParts mutiple times, so it's useful to put it into it's own function
	local p1 = randParts(1)[1]
	p1:Destroy()
	local tab = randParts(10)
	for q=1,#tab do
		local decide = math.random(1,2)
		if decide == 1 then
			tab[q]:Destroy()
		else
			tab[q].BrickColor = BrickColor.Blue()
		end
	end
end

This discussion is preserved as it was. New answers, comments, and votes are closed.