I have a script inside a part named 'SlideTrigger' and when it touches the part it should make you sit but in the output, it says 'Workspace.SlideTrigger.Script:5: attempt to index global 'player' (a nil value)'
Can someone help, any help helps me.
1 | local player = game.Players.LocalPlayer |
2 |
3 | workspace:FindFirstChild( "SlideTrigger" ).Touched:connect( function (hit) |
4 | print ( "Touched, now sitting" ) |
5 | workspace [ player.Name ] .Humanoid.Sit = true |
6 | end ) |
LocalPlayer is only available in a LocalScript. Though, you can use the "hit" variable from the Touched event for a clue of who's the player. Example:
1 | workspace:FindFirstChild( "SlideTrigger" ).Touched:connect( function (hit) |
2 | if game.Players:GetPlayerFromCharacter(hit.Parent) then --Players:GetPlayerFromCharacter() returns nil when the model isn't a player's character. |
3 | print (hit.Parent.Name .. " is sitting!" ) |
4 | hit.Parent.Humanoid.Sit = true |
5 | end |
6 | end ) |
Try using a Seat instead of a normal part ;)
Insert a script into the part you want to be touched and then insert this script if you want a player to sit and fall.
1 | script.Parent.Touched:connect( function (hit) |
2 | if hit.Parent:FindFirstChild( "Humanoid" ) then |
3 | hit.Parent.Humanoid.Sit = true |
4 | end |
5 | end ) |
If you want a player to sit on the seat then I recommend you insert a seat.
Easy mate, no worries.
Where you went wrong:
You're trying to access localplayer through a script, yet that's only possible with localscripts. Instead, you can get the player from character through "game.Players:GetPlayerFromCharacter()".
A character is a model containing the humanoid, arms, legs, torso, and scripts of a player's character. Initially this property is set to nil, and is set when the player's character spawns.
The hit in a function using the touched event will be inside the character, so therefor, the character itself is the parent of the hit.
The fixed script would look like this:
1 | workspace:FindFirstChild( "SlideTrigger" ).Touched:connect( function (hit) |
2 | local player = game.Players:GetPlayerFromCharacter(hit.Parent) |
3 | print ( "Touched, now sitting" ) |
4 | workspace [ player.Name ] .Humanoid.Sit = true |
5 | end ) |
A more simpler script would be like this
1 | workspace:FindFirstChild( "SlideTrigger" ).Touched:connect( function (hit) |
2 | print ( "Touched, now sitting" ) |
3 | hit.Parent:WaitForChild( "Humanoid" ).Sit = true |
4 | end ) |