Hi

I'm making a very simple race against the clock game. The player has to run a very simple course, and they see their time updated every second. There is a part on the finish line which, when they touch, can tell them their finish time.

There is a script in the finish line part which holds a variable called raceactive. This is set to false when you hit the finish part, but before then it updates the elapsed time (in seconds) on a screengui in the startergui.

The difficulty I am having is finding the player name so I can refer to the screengui. If I use the following, then I get a message "attempt to index field 'LocalPlayer' (a nil value)"

local player=game.Players.LocalPlayer.Name

However if I hard code my username (see below) then the script does what I would like it to do

local player=game.Players.myname

Grateful for any help people can offer. The whole script is below.

Many Thanks

Chris


-- Keep track of time the racer has been running

local timepassed=0 -- timer variable local finishLine=script.Parent -- finsih line part local raceactive=true -- testing if race is active -- local timergui=game.StarterGui.TimerGui.TimerText -- The Gui for the timer -- print (timergui.Text) -- wait(2) -- print (timergui) -- timergui.text="Changing the text"

-- Function which is run at the end of the race local function finish() if raceactive==true then print ("You finished in "..timepassed.." seconds") raceactive=false -- sets flag to end the race

end

end

-- Function for when the finish line is touched

local function partTouched(otherpart) local character=otherpart.Parent local humanoid=character:FindFirstChildWhichIsA("Humanoid") if humanoid then finish()

end

end

-- When finishline is touched, call the partTouched function finishLine.Touched:Connect(partTouched)

-- The race timer

while raceactive==true do wait(1) timepassed=timepassed+1 -- Increment the timer -- local players=game:GetService("Players").LocalPlayer local player=game.Players.LocalPlayer.Name print (player) -- local player=game.Players.redchris999 local PlayerUI = player:WaitForChild("PlayerGui") local ScreenGui = PlayerUI:WaitForChild("ScreenGui"); local TextLabel = ScreenGui:WaitForChild("TimerText"); -- print (TextLabel.Text) TextLabel.Text=timepassed.." seconds have passed "..player.Name end


2 comments

0

that's because you have this in the normal script (I assume) where you can't use LocalPlayer, if you want to do so then you need to use LocalScript, tho keep in mind that local scripts only work inside - ReplicatedFirst, PlayerGui, StarterPlayerScripts, StarterCharacterScripts, player/character model and player backpack

0

Thanks TopBagon. That is really useful : I didn't know that about local scripts. The script I am trying to run us attached to a part in workspace, so I am assuming I can use a local script. In that case what is the best way to identify the player name? Thank you.