Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

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

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

✓ Accepted answer

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.

4 comments

0

It works perfectly fine, It's just that I don't really like using couretines, Is there a way without using them?

0

You can use the spawn function it acts very similar to a coroutine.

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.

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.

This discussion is preserved as it was. New answers, comments, and votes are closed.