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
3 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

    local playersIn = {}

    local string1 = game.Workspace.player1

    game.Workspace.red.Touched:Connect(function(hit)
        if hit.Parent:FindFirstChild("Humanoid") then
            table.insert(playersIn, hit.Parent)
        end
    end)


    for i, v in pairs(playersIn) do
        if v[1] then
            while true do
                wait()
            string1.Value = v[1].Name
            end
        end
    end

1 answer

Log in to vote
1
Answered by 3 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:

local playersIn = {}

local string1 = workspace.player1

local connection 

local function onTouched(hit)
    if hit.Parent:FindFirstChild("Humanoid") then
        local player = game:GetService("Players"):GetPlayerFromCharacter(hit.Parent)
        table.insert(playersIn, player)
        connection:Disconnect()
    end
end

connection = workspace.red.Touched:Connect(onTouched)


coroutine.wrap(function()
    while true do
        if playersIn[1] then
            string1.Value = playersIn[1].Name
        end

        wait()
    end
end)()

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 — 3y
0
You can use the spawn function it acts very similar to a coroutine. JesseSong 3916 — 3y
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 — 3y
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 — 3y
Ad

Answer this question