Hello there im having problems picking a random magic from a table using math.random. Youtube wont help me so i want to ask u guys for help.
function OnPlayerAdded(Player) Player:WaitForDataReady() Player = game.Players.LocalPlayer Magic = Instance.new("StringValue", Player) Magic.Name = "Magic" if Player:LoadString("Magic") ~= "" then Magic.Value = Player:LoadString("Magic") else Elements = {"Water", "Fire", "Earth"} i = math.random(1, #Elements) Player.Magic.Value = Elements[i] Player:SaveString("Magic" , Player.Magic.Value) M = Instance.new("Message", workspace) M.Text = Magic.Value game.Debris:AddItem(M, 5) end if Player.Magic.Value == "Fire" then x = game.Lighting.Fireball:clone() elseif Player.Magic.Value == "Water" then x = game.Lighting.Waterball:clone() elseif Player.Magic.Value == "Earth" then x = game.Lighting.Rockball:clone() end x.Parent = Player.Backpack end game.Players.PlayerAdded:connect(OnPlayerAdded)
Assuming you have this as a Script, you don't need the third line as you can't access the LocalPlayer from a server script. Plus, you wouldn't need to use the LocalPlayer anyway as you're already getting the player from the PlayerAdded event.
Another reason you shouldn't use a LocalScript for you code is because LocalScripts can't handle data persistence saving and loading as it is server sided. I would also make your variables in the function local as variables can conflict if a new player enters.
Also, I believe WaitForDataReady is broken, so I took it out of your script.
The final script is below:
Elements = {"Water", "Fire", "Earth"} --Have Elements outside the script for ease. function OnPlayerAdded(Player) local Magic = Instance.new("StringValue", Player) Magic.Name = "Magic" if Player:LoadString("Magic") ~= "" then Magic.Value = Player:LoadString("Magic") else local elem = math.random(1, #Elements) --I recommend you use local variables so that variables don't conflict. Magic.Value = Elements[elem] Player:SaveString("Magic" , Magic.Value) M = Instance.new("Message", Player.PlayerGui) --Put message in PlayerGui so that only the player can see it. M.Text = Magic.Value game.Debris:AddItem(M, 5) end if Magic.Value == "Fire" then local x = game.Lighting.Fireball:Clone() x.Parent = Player.Backpack elseif Magic.Value == "Water" then local x = game.Lighting.Waterball:Clone() x.Parent = Player.Backpack elseif Magic.Value == "Earth" then local x = game.Lighting.Rockball:Clone() x.Parent = Player.Backpack end end game.Players.PlayerAdded:connect(OnPlayerAdded)
I would suggest using DataStores for your data saving/loading as Data Persistence is quite old now.
I hope my answer helps you. If it did, be sure to accept it.