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

How do I make a function start when the first player in the server joins?

I have already looked this up on the web, but it's not helping me.

3 answers

local Players = game:GetService("Players")

local function OnPlayerAdded(Player)
	print(Player.Name)
end

Players.PlayerAdded:Connect(OnPlayerAdded)

2 comments

0

Honestly, I dont get it, here's what I did my script as.

0

local Players = game:GetService("Players") local function OnPlayerAdded(Player) print(Player.Name) script.Parent.Text = "Hello" end Players.PlayerAdded:Connect(OnPlayerAdded)

While Feahren's answer does answer the question of how to fire an event when a player joins, the event will fire every time a new player joins. You would have to make a slight change in order for it to fire when the first player joins.

local players = game:GetService("Players")

--When a player joins
players.PlayerAdded:Connect(function(player)
	--If they are the first person to join (there is only one player in the game)
	if #players:GetPlayers() == 1 then
    	--Put the function here
	end
end

Hope this helps.

I saw your comment on Feahren's post. You want to add text to a Gui. Feahren's script was just fine, but it is meant to be in a normal script. If you want to script something for the Gui, you need to put it in a LocalScript. You need to at least tell us what you are going to do first, so we can give you the answer you need right away. Anyways, insert a RemoteEvent in ReplicatedStorage. Then make sure your original script is a LocalScript in your Gui, and insert a normal script in ServerScriptService. I will show you what is happening in the scripts:

Script in ServerScriptService

game.Players.PlayerAdded:Connect(function() -- Whenever a player joins the game
	if #game.Players:GetPlayers() == 1 then -- if number of players is 1 because you don't want this to keep executing whenever more players join
		game.ReplicatedStorage.RemoteEvent:FireClient() -- fires LocalScript to execute whatever code it has
	end
end)

LocalScript

game.ReplicatedStorage.RemoteEvent.OnClientEvent:Connect(function() -- LocalScript can access a player's Gui while the server cannot. This is the event that you want
	script.Parent.Text = "Hello"
end)

Hope this helps!

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