Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
3

The String's Value won't change to Player's Name?

Asked by
Borrahh 265 Moderation Voter
4 years ago

Basically, when players touch "Red" they should join on a table, and if there is a player inside, the String's Value should change to Player's Name

01local playersIn = {}
02 
03local string1 = game.Workspace.player1
04 
05game.Workspace.red.Touched:Connect(function(hit)
06    if hit.Parent:FindFirstChild("Humanoid") then
07        table.insert(playersIn, hit.Parent)
08    end
09end)
10 
11 
12for i, v in pairs(playersIn) do
13    if v[1] then
14        while true do
15            wait()
16        string1.Value = v[1].Name
17        end
18    end
19end

1 answer

Log in to vote
1
Answered by 4 years ago

Hello. The problem is that you used an in pairs loop which would run before the touched event fires which would mean the loop wouldn't find anything in the table so it would go on with the rest of the script. Instead, use a coroutine with a while true do loop which checks if a player is in the "playersIn" table. Also, I used a connection variable with :Disconnect() to prevent other players getting added to the table. Try this:

01local playersIn = {}
02 
03local string1 = workspace.player1
04 
05local connection
06 
07local function onTouched(hit)
08    if hit.Parent:FindFirstChild("Humanoid") then
09        local player = game:GetService("Players"):GetPlayerFromCharacter(hit.Parent)
10        table.insert(playersIn, player)
11        connection:Disconnect()
12    end
13end
14 
15connection = workspace.red.Touched:Connect(onTouched)
View all 26 lines...

Coroutines are a way to use code without yielding the rest of the script. Please upvote and accept this answer if it helped.

0
It works perfectly fine, It's just that I don't really like using couretines, Is there a way without using them? Borrahh 265 — 4y
0
You can use the spawn function it acts very similar to a coroutine. JesseSong 3916 — 4y
0
Also youtubemaster theres no point of referencing the player who hit the part on line 9 because its already been referenced on line 8. JesseSong 3916 — 4y
0
Yes I know. And, DO NOT USE THE SPAWN FUNCTION. It is a bad habit since there can be delays and you should really just use coroutines instead of spawn. youtubemasterWOW 2741 — 4y
Ad

Answer this question