So, I'm trying to make a script that if a part is touched, it does something, but, it has to be a player touching the part... How to verify if a player is touching the part?
1 | script.Parent.Touched:connect( function (playerlol) |
2 | playerlol.Parent.Humanoid.WalkSpeed = 100 |
3 | playerlol.Parent.Humanoid.JumpPower = 80 |
4 | game.Workspace.Gravity = 100 |
5 | game.Workspace.Song:Play() |
6 | end ) |
One way is to just check if what hit has a humanoid. The other way is to see if the name of what hit is a player, I combined them both here.
1 | script.Parent.Touched:Connect( function (playerlol) |
2 | if playerlol.Parent:FindFirstChild( "Humanoid" ) and game.Players [ playerlol.Parent.Name ] then |
3 | print "is a player" |
4 | playerlol.Parent.Humanoid.WalkSpeed = 100 |
5 | playerlol.Parent.Humanoid.JumpPower = 80 |
6 | game.Workspace.Gravity = 100 |
7 | game.Workspace.Song:Play() |
8 | end |
9 | end ) |
However, like Avigant said, playerlol.Parent could be nil, so to account for this there's an other way to test if it's a character. This is by using GetPlayerFromCharacter()
which returns the player associated with the given character.
To use it, write the following code.
1 | script.Parent.Touched:Connect( function (playerlol) |
2 | if playerlol.Parent and game:GetService( "Players" ):GetPlayerFromCharacter(playerlol.Parent) then |
3 | print "is a player" |
4 | playerlol.Parent.Humanoid.WalkSpeed = 100 |
5 | playerlol.Parent.Humanoid.JumpPower = 80 |
6 | game.Workspace.Gravity = 100 |
7 | game.Workspace.Song:Play() |
8 | end |
9 | end ) |
You'd use the game.Players:GetPlayerFromCharacter()
method to test.
1 | BasePart.Touched:Connect( function (TouchedPart) |
2 | if not game.Players:GetPlayerFromCharacter(TouchedPart.Parent) then |
3 | return |
4 | end |
5 |
6 | -- It's a player! |
7 | end ) |
Remember that TouchedPart.Parent
can always be nil
.
You can check if a player is touching by adding if playerlol.Parent:FindFirstChild("Humanoid")
I've fixed your script, it should look like this:
1 | script.Parent.Touched:Connect( function (playerlol) |
2 | if playerlol.Parent:FindFirstChild( "Humanoid" ) then |
3 | playerlol.Parent.Humanoid.WalkSpeed = 100 |
4 | playerlol.Parent.Humanoid.JumpPower = 80 |
5 | game.Workspace.Gravity = 100 |
6 | game.Workspace.Song:Play() |
7 | end |
8 | end ) |