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

How do I update a gui when I add one to a variable in it?

Asked by 8 years ago
score = 0
brick = game.Workspace.Part
gui = game.StarterGui.ScreenGui.TextLabel

gui.Text = "Score: " .. score

function touch(part)
    score = score + 1
    gui.Text = "Score: " .. score
    brick:Destroy()
end

brick.Touched:connect(touch)

This is my code that I tried to use to show the score on a gui. The score stays 0 when I touch the brick. When i do go to the properties of the textlabel, it says the property text has the value of "Score: 1" but it does not show up on the screen.

1 answer

Log in to vote
1
Answered by 8 years ago
Edited 8 years ago

StarterGui is a folder that stores things to be given to the player - it does not control the actual GUIs the player is seeing. You will find that respawning updates the gui, because StarterGui will by default clear the player's PlayerGui, then clone StarterGui's content into it.

As well as this, this will update the GUI for all players, something which I believe you do not want to happen from look at your code.

Here's the fixed version of the code:

local part = workspace:WaitForChild("Part") --// WaitForChild makes sure that the part is loaded before trying to index it
local playerScores = {} --// For later use, note that this style is not recommended in most cases, but will accomplish what you need

part.Touched:connect(function(hit)
    local player = game.Players:GetPlayerFromCharacter(hit.Parent)
    if player then --// If what touched the part was from a player
        local gui = player.PlayerGui:FindFirstChild("ScreenGui") --// Sees if the GUI exists before attempting to index it (will error otherwise)
        if gui then --// If the GUI does indeed exist
            local text = gui:WaitForChild("TextLabel") --// Waits for the TextLabel
            if not playerScores[player] then --// If a player does not have a set score
                playerScores[player] = 0 --// Sets the value if it does not exist
            end
            playerScores[player] = playerScores[player] + 1 --// Adds 1 to the score
            text.Text = "Score:" ..playerScores[player] --// Sets the text
        end
    end
end)

Hope I helped! If you need more help, please ask.

~TDP

Ad

Answer this question