Let’s assume I have 2 “Touched Event” scripts in my part. Here are they:
Script 1:
local Part = script.Parent
local Coin = game.StarterGui.CoinGui.CoinLabel
Part.Touched:Connect(function()
Coin.CoinValue.Value = Coin.CoinValue.Value + 100
end)
Script 2:
local Part = script.Parent
Part.Touched:Connect(function()
local Coin = game.StarterGui.CoinGui.CoinLabel
Coin.CoinValue.Value = Coin.CoinValue.Value + 100
end)
Is there a necessary difference if I define the coin label in the event instead of defining it at the start of the script?
Not much difference aside from the one at the top being more performant since you aren’t reevaluating the path of the instance, and the one at the bottom being vulnerable to “index nil” errors (the instance could be missing for some reason at the time of the event)
Not related to your question but whenever you declare the path to an instance, it is better to use WaitForChild() to avoid “is not a valid member of” errors.
As for your question, it really depends on what you want to do. If you are going to change the value of that instance or variable or you need it in multiple different functions, simply declare it at the top of your script, such as whenever you need a service.
local Players = game:GetService("Players")
Players.PlayerAdded:Connect(function(Player)
I’ve found that for me it reduces the chance of internal lag on waiting for the game to find that service AND firing an event on the same line. Hope this helps!
Depends on who you ask and what scripter they are. You can use Game.Players but the Players service isn’t the first thing to load into the client / server so it may not exist for some time. By getting the service with :GetService allows a guaranteed result to get the right service right away. This difference in the player service isn’t too noticeable, but it’s a good practice to get into and it’s not a bad habit. (Because to name a few, you will need to GetService() for a couple services to name a few like, TweenService, UserInputService, DatastoreService, MarketplaceService. All need to be gotten with :GetService)
They are different ways to get the same Result. game.players and game:GetService(“Players”) are the same thing as they mention the Service called Players. They work a tad differently internally as by getting the with GetService(), makes sure that the service is loaded and available in simple terms, with game.Players having a small risk where the service isn’t loaded in yet. With the Player and workspace service usually isn’t too noticeable, but it could be important for other services