I’d just like to elaborate on the examples slightly, because they are excellent ones.
Ok, here you can see that we are in a localscript. The comment below explains that leaderstats may not have loaded yet. By this, @VegetationBush means that the object was created on the server. In order to keep clients in sync, Roblox’s server replicates objects to the client. However, your code needs to interact with these. Attempting to operate on an object which has not loaded will result in the Attempt to index a nil value
error we all kind of hate.
To fix this, we need to wait for the thing to be confirmed as loaded. Luckily, Roblox gives us this function.
A note on it, though. It should be used sparingly. The performance impact of this is slightly higher than just indexing normally. In addition, doing this in code which needs to run fast is bad because of the yield.
In essence, in order to keep your performance high, use this function once and keep a reference to the returned result. This ensures that the object was replicated. So, for example, use the function to get the leaderstats in a variable and then use that variable from then on. It’s not good practice to continually WaitForChild
for the exact same instance. It’s a waste of performance, don’t do it.
In this example, the hit’s parent could be any instance. It could be workspace, it could be a generic model or even some random part. So, we can’t assume the object is there. This function allows us to check this.
In Lua, if nil
is passed as the value to an if statement, it will be treated as though it were false. So, basically, if there is no humanoid, we get false back.
This allows us to discard hits from non-players.