I am not sure what the best way to go about this would be, but I want to access the player from a server script. The game I am working on is a single player game, so no other players would be in the game. This is what I have been using to get the player, but the problem is that the player returns nil because the script runs before the player loads in. My question is how can I get around this and is this a decent solution to my problem or is what I am doing considered bad practice?
local Players = game:GetService("Players"):GetPlayers()
local player = Players[1]
For reference this is a script under an enemy, and I need the script to award that player with coins on the death of the enemy. Is my way of doing this a decent idea?
Oops, I forgot to mention something. I was trying to avoid using the PlayerAdded event because it only fires once when the player is added, but I have this script under the enemy model which is spawned in multiple times, so the code only executes when the first enemy spawns in but not if more are spawned in.
Yeah i messed around with that second option already but couldn’t figure out how to return the actual player, because all that gets returned is a Connection.
If you wanna do this all on the server there’s a few things I can think of one of them is to have a module script with a player variable which can then be accessed by any other script that require the module. You could also use bindable events and have a GetPlayer event which returns the player. You could also use collection service to tag the player when they join and then use GetTagged(Tag Name) (I think) which will return a table of everything with that tag this also replicates to the client if you needed the tag for anything else. Lastly I’m pretty sure as long as the player loaded you can just do game:GetService(“Players”):GetPlayers()[1]
Edit: Before doing any of these just make sure the player does exist by using PlayerAdded or repeat or something to wait for it and then you can set it to a variable or tag it