How do I make this script work?

Hello Developers!
I was making my game and wanted to print something if the owner joins. The script was not working and I didn’t know how to fix it. The script is in ServerScriptService and it was a regular script not a module, or Local script.

local player = game.Players.LocalPlayer
if player.Name == "TrackoTheTaco" then
	print("test")
end

Instead of this make a Script in ServerScriptService and try this:

game.Players.PlayerAdded:Connect(function(player)
   if player.Name == "TrackoTheTaco" then
      print("test")
   end
end)

Let me know if it works, if it does then mark it as the solution so others know.

What the script does is when a player joins the game and the player name is “TrackoTheTaco” it will print(“test”), if you want it to be a local script then you can do the same but instead of a script put the code in a local script in StarterPlayerScripts inside of StarterPlayer. :slightly_smiling_face:

3 Likes

I Tried it and it did not print anything in the output so I typed in the chat “/console” and nothing got printed.

There was an error in the script, try it again I fixed it now.

The issue here is that you are trying to run game.Players.LocalPlayer inside of a Server Script, which would not work, as it is not a local script. You can trying using player.UserId to achieve this:

local Player = game:GetService("Players"):GetPlayerByUserId() --Insert your userid here
 
if Player then
    print("Test.")
end```

I tried it again, And it did not work.

I Just tried this with my user ID and it did not work, Nothing got printed.

Your solution works but it has a flaw in it, the script can run very fast before the player even joins the game and it will just error because it couldn’t find the player.

But if you use my solution it will never error because I made it so when the player joins the game the code inside it will fire.

Did you try inserting your userid into the brackets?

That was good feedback, I’ll take note of that for later reference. Thank you.

1 Like

Yep, That’s what I did, I inserted my profile ID into the brackets and nothing got printed.

I can confirm that it does work for me as shown below:

Do you have any other scripts/local scripts or any other code inside of the script/local script that might stop it from working?

Because it’s working for me like you saw.

Hmm, Weird… It wasn’t working before but now it is.

1 Like

Alright, I did something similar, use a PlayerAdded Event

Make sure your script runs of UserId because name changes are always possible.
Dont use the predefined variable for player. Instead, try using this:

game.Players.PlayerAdded:Connect(function(plr)
    if plr.UserId == "Put the ID here" then
	   print("Test.")
    end
end)

This should work.

Edit: Delete the quotes when inserting UserId numbers.