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