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

Can someone help me with this teleport problem?

I'm trying to choose two random players to fight and teleport them to the map, but an error occurs. I'm trying to make sure opponent1 and opponent2 are NOT the same person then tele them to the map.

I'm trying to make a 1v1 sword fight game

The error: ServerScriptService.Main:44: attempt to index local 'opponent1' (a number value)

Code:

wait()

local players = game.Players:GetPlayers()

local maps = game:GetService("ServerStorage").Maps:GetChildren()

local runningmaps = workspace:WaitForChild("RunningMaps")

function hint(text)
	for i, player in pairs(players) do
		player:WaitForChild("PlayerGui").MainGui.hint.Text = tostring(text)
	end
end

function shout(text)
	for i, player in pairs(players) do
		player:WaitForChild("PlayerGui").MainGui.shout.Text = tostring(text)
	end
end

while true do
	hint("Welcome to Sword Fighting Practice!")
	wait(3)
	hint("Intermission: 15 seconds")
	for i=15,1,-1 do
		hint("Intermission: " ..i.. " seconds")
		if i < 2 then
			hint("Intermission: " ..i.. " second")
		end
		wait(1)
	end
	hint("")
	shout("Choosing a random map...")
	randommap = math.random(1,#maps)
	mapchosen = maps[randommap]
	wait(3)
	shout("Map Chosen: " ..mapchosen.Name)
	wait(3)
	local mapClone = mapchosen:Clone()
	mapClone.Parent = runningmaps
	local opponent1 = math.random(1,#players)
	local opponent2 = math.random(1,#players)
	local spawns = mapClone:WaitForChild("Spawns")
	if opponent1.Name ~= opponent2.Name and opponent2.Name ~= opponent1.Name then -- Error starts here
		for i,v in pairs(opponent1, opponent2) do
			if spawns then
				opponent1.Character:WaitForChild("Torso"):MoveTo(spawns.Position)
			end
		end
	else
		repeat local opponent1 = math.random(1,#players) local opponent2 = math.random(1,#players) wait() until opponent1.Name ~= opponent2.Name and opponent2.Name ~= opponent1.Name 
	end
	--for i,v in pairs()
	wait()
end

1 answer

✓ Accepted answer

When you define opponents you use math.random which will return a number; to get an actual player object you will need to use players[math.random(1,#players)]. This is because math.random(1,#players) will give a random number from 1 to the number of players. Using players[x] will give you the player object in the position of x.

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