If i want a script to run everytime a Player spawns. What’s the most efficient way of doing it?
Like this?
local Players = game:GetService("Players")
local CharacterAdded = function(Character)
-- Script
end
local NewPlayer = function(Player)
Player.CharacterAdded:Connect(CharacterAdded)
end
Players.PlayerAdded:Connect(NewPlayer)
You’d be better off putting it in StarterCharacterScripts, it gets deleted and spawned back into the character every time the character spawns. To get the player from there just do this, no need to use PlayerAdded or CharacterAdded:
local char = script.Parent
local player = game.Players:GetPlayerFromCharacter(char)
I mean both work, and have it’s own reasons why you way use the event & reloading the script.
There are slight differences for example, technically speaking, using the event is better, as roblox wouldn’t have to load the instance of the script each time. In otherwords, the event would be fired, before the cloned script is loaded and ran , So its a tad more efficient, as it wouldn’t “yield”. Also, the event personally is nice, like if you were to track the number of times the character is added with no Int/Number values, and only variables, This would be really easy to track with the event, then recloning the script. Also it’s easier to read, per say making a developer forum post on your code. Using the character event tells other people that it is ran when a new character is added, instead of explaining that it exists in StarterCharacterScripts. It really depends how you will use it. And while they are slightly different, it doesn’t matter too much.
If you are dealing with Server related Scripts. You use CharacterAdded, and store it somewhere safe, so it isnt stolen, however if you are Dealing with Client related Scripts, it can br a mix of both, i would say StarterCharacterScripts on something that is important to the character, like Aninations, or Ragdoll effects.
However if you are just managing data around CharacterAdded would be more convenient for this purpose.
But 99% of the time. You use CharacterAdded and not StarterCharacterScripts , due to its convenience, and ability to be used anywhere, Just make sure you keep your important code safe.
If they are essential to having your game run, I would suggest moving to somewhere the Client cant access like ServerStorage or ServerScriptService, where the Server does not replicate its children to the Client, However if they are just hold Data for Stuff like Effects, Sounds, basically anything Misc, you shouldn’t really need to worry about it.
Both Server Script and ModuleScript can be stolen if you allow them to access it, which is why you store them safely like what I stated above.