I need some help with this script I have. I wanted to say for example if the player's name is ExampleHere i would like to say ";kill Exa" and have it kill the player, but, it doesn't work. Code:
game.Players.PlayerAdded:connect(function(player) if player.Name == "KDarren12" then player.Chatted:connect(function(msg) if string.sub(msg, 1, 5) == ";kill" and game.Players:FindFirstChild(string.sub(msg, 6)) then game.Players:FindFirstChild(string.sub(msg, 6)).Character.Humanoid.Health = 0 end end) end end)
Can I get some help please?
The easiest way to go about what you're trying to do is to use string.find. What you want do do is to loop through the list of Players in the game, and pass the string provided and the players name
function findPlayer(str) for _, player in pairs(game:GetService("Players"):GetPlayers()) do if string.find(player.Name, str) == 1 then return player end end return "Could not find player!" end
What this does is for each player in the game it compares their name to the string you pass. string.find returns 0, 0
when it doesn't find a match, but it will return startPosition, endPosition
when it does find it. Since you will always be starting with the beginning of the player's name, the startPosition
will always be 1
. This means we only have to check the first value even though two are returned
Implementing this into what you currently have would look like so:
local Players = game:GetService("Players") function findPlayer(str) for _, player in pairs(Players:GetPlayers()) do if string.find(player.Name, str) == 1 then return player end end return "Could not find player!" end Players.PlayerAdded:connect(function(player) if player.Name == "KDarren12" then player.Chatted:Connect(function(msg) if string.sub(msg, 1, 5) == ";kill" then local playerToKill = findPlayer(string.sub(msg, 6)) if type(playerToKill) ~= "string" then -- This is to make sure it returns a player and not an error playerToKill.Character.Humanoid.Health = 0 end end end) end end)