Hi reader, I was wondering how I can fix up this script, It's using math.random to choose a random player out of the players. It's coming up with errors saying 'Attempt to index local killer a number value' but I don't want it to be a number, I want it to be the chosen players name. I was wondering if anyone could help fix my script.
for i, player in pairs (game.Players:GetPlayers()) do local Killer = math.random(1,1) workspace[Killer.Name]:MoveTo(game.Workspace.spawntest) end
math.random returns numbers, not players. With this, you can use select a random player from a list of players.
local Players = game.Players:GetPlayers() -- This list won't automatically update, so be sure to run this again after any time has passed. local Killer = Players[ math.random(#Players) ] --This generates a random number between 1 and the number of players, and uses that as an index to select the player from the list. Killer.Character:MoveTo(game.Workspace.
You should also put math.randomseed(tick())
before you generate random numbers to make them seem more random. Random numbers generated by computers aren't truly random, but using a unique number as a seed will make the output appear random.
Edit: The # operator only works on tables. In this case, the table it applies to is Players - a list created by calling game.Players:GetPlayers()
. You don't need a loop to do any of this.
Ok then.
It looks like you (for whatever reason) expected math.random()
to give you a userdata rather than an integer.
So for starters, lets create a valid example of how to use math.random()
. Say I want to print a random number from 1 through 10
num = math.random(1,10) print(num)
or
print(math.random(1,10))
What about choosing a random userdata!??!
We're getting there, first I want to do a little briefing on tables:
tab = {} -- tab is our table table.insert(tab,'oof') -- this inserts the string "oof" into our table print(#tab) -- this will print the length of the table print(tab[1]) -- this will print the first value of the table, which is "oof" table.remove(tab, 1) --this removes the first value of the table
Now we're there!
Now, if this is a script in game.ServerScriptService
:
plrs = {} game.Players.PlayerAdded:Connect(function(plr) table.insert(plrs, plr.Name) end) game.Players.PlayerRemoving:Connect(function(plr) for i,v in pairs (plrs) do if v == plr.Name then table.remove(plrs,i) end end end) function pickrandomplayer() local num = math.random(1,#plrs) workspace[plrs[num]]:MoveTo(game.Workspace.spawntest) end
Then you run pickrandomplayer()
whenever you need to pick a player.
Note: You should probably research the roblox wiki before you ask questions here.