I just want to know what the purpose of assigning empty variables and how to use them. Thank you.
Usually when someone assigns an empty variable, they clarify it in another part of the script such as if someone needed to get a humanoid when they touch a part
local humanoid
if part.Parent.Humanoid then
humanoid = part.Parent.Humanoid
elseif part.Parent.Parent.Humanoid then
humanoid = part.Parent.Parent.Humanoid
end
When I use part.Parent.Humanoid that’s just saying if it’s touching usually a leg or an arm it can find the humanoid from there
when I say part.Parent.Parent.Humanoid that usually means that i’m trying to find the humanoid that touched an accessory aka a hat of some sort.
It’s not just cosmetic, it’s very useful for controlling the scope of variables. If a programmer wants to be able to access a variable from anywhere in the script, it will typically be declared at the top of the script.
It might make sense to not to assign anything to the variable for a couple of reasons. One reason is that it might just be part of the normal way the script is supposed to function, e.g. the script might periodically check if an instance exists inside a parent with the FindFirstChild method, which returns nil if nothing is found. A different part of the script can then just check if that variable is nil
. A
nother example is when the thing that the variable is supposed to refer to doesn’t exist yet, or needs to be set after some other part of the code has run.
This isn’t a great example because it will error if the Humanoid doesn’t exist. It won’t ever run the code under else
.
As @posatta pointed out, you should use :FindFirstChild()
checking if something is a descendant of something. Another alternative would be to use :IsDescendantOf()
function to check.
One use case I use often is when disconnecting events:
local Connection
Connection = game:GetService("RunService").Heartbeat:Connect(function()
Connection:Disconnect()
end)
With the code above creating a black variable and then assigning an event to it will allow you to then disconnect it in the scope of the function. This means when you run the code above the heartbeat event will only fire once.
Yeah, I just wrote up some simple code for this real quick.