How do I check if a character has a Player?

Hello developers. Note: I am a noob scripter. I do not know much about the words and terms used to describe things in the scripting language. Anyways I was gonna make a spike for my game to damage players and horses. So don’t ask me why but I want to check if the character has a player like game.Players:GetPlayerFromCharacter(Character). Can I use **if not game.Players:GetPlayerFromCharacter(Character) then ** to check if the character has a Player?

1 Like

Yeah you can do that.

Also move this post into #help-and-feedback:scripting-support

Thank you for your reply! This is the first topic I ever made on the Devforum. I will go test it out thank you!

You can do something like this

local part = script.Parent
part.Touched:Connect(function(hit) -- Fires the event if the part has been touched
          local plr = game.Players:GetPlayerFromCharacter(Character) -- gets the character from player
          if plr ~= nil then --Checks if player is a character (returns nil if its not a character)
                  -- Do something
          end
end)
3 Likes

Thank you! I just came back from testing! It works. Here is my script. local HumanoidToFind = “Humanoid”

script.Parent.Touched:Connect(function(hit)
if hit and hit.Parent:FindFirstChild(HumanoidToFind) then
local Character = hit.Parent
if game.Players:GetPlayerFromCharacter(Character) then
print(“Player found!”… hit.Parent.Name)
else
print(“Player not found”… hit.Parent.Name)
end
end
end)

I am new to devforum. How do I type in my script like yours where its organised?

No problem! You can mark my reply as a solution (the solution button is right next to the reply button)

Tip: Put the ``` at the beginning and put it at the end of a script that you are sharing

1 Like

Oh yeah I understand part of your script but what does “nil” mean? I do not understand what “~= nil” or “= nil” means.

It checks if the player exists.

Could you explain it more clearly on what it means? It checks if the player exists but what does it mean exactly?

The “~=” sign basically means if its not something which means that “~= nil” is if its not nil

1 Like

nil means that it doesn’t exist, you should most of the times check if things are nil or not to prevent errors (you cant update or change something that doesn’t exist!!)

1 Like