Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

Player.WaitForChild("Character") obv doesn't work, but what could be used instead of it ?

Asked by
Khanon 10
4 years ago
Edited 4 years ago

My code works fine... its this one:

script.Parent.Touched:connect(function(hit)

    for i,v in pairs(game.Players:GetPlayers()) do
        v.Character.UpperTorso.Transparency = v.Character.UpperTorso.Transparency + 0.1
    end


end)

But I also get the following error :

attempt to index field 'Character' (a nil value)

How do I solve it ? Why is v.Character a nil value ? Doesn't the GetPlayers function return only players as v values? I think every player should have a character... is it maybe that some characters arent loaded yet when the function is fired for the first time ? Because this part is not anchored and the baseplate it stays on is anchored...

Still.. I can't do v.WaitForChild("Character") , is there any other ways for me to prevent getting this error ? It is a harmless one but I'd love to get completely rid of it.

Edit1 : I don't want to check if the toucher has a Humanoid or not.. Cuz There could be a person touching this brick when someone else was newly joining and I'd get an error cuz the new players character wouldn't have been loaded...

Edit2 : The right answer came fast, and it was clear, but I want to add something for people wandering around to also understand.. The correct solution is

script.Parent.Touched:connect(function(hit)

    for i,v in pairs(game.Players:GetPlayers()) do
        local charac = v.Character or v.CharacterAdded:wait()
        charac.UpperTorso.Transparency = charac.UpperTorso.Transparency + 0.1
        print("done")
    end



end)

but the important part is that as the answerer mentioned, it jumps to the second argument of OR when v.Character gives nil...

When you do this; local charac = v.CharacterAdded:wait() or v.Character as in.. Opposite order The script wont work correct when you have loaded characters, instead, it will only work when there are some unloaded characters...

1 answer

Log in to vote
0
Answered by
Elixcore 1337 Moderation Voter
4 years ago
Edited 4 years ago

It's quite simple.

When you are trying to get the character and are unsure if it's there, you use player.CharacterAdded.

The event will return the character as soon as it is fired, so this in combination with a check for the player.Character will always return the character no matter what.

local character = player.Character or player.CharacterAdded:Wait()

If player.Character returns nil, it will move onto the event and wait for it to return the character when it is fired, as it is a yielding event, thanks to :Wait().

1
Ah sorry and thanks.. I could have checked the API, and did, but somehow couldn't see... Khanon 10 — 4y
0
It's a very common problem for beginners, don't worry about it. Elixcore 1337 — 4y
Ad

Answer this question