Hello, I ran into a problem that I managed to find the solution for. But I still require information on why this problem occurred in the first place.
I have a simple script intended for testing, I made it simple because my previous script was a combat system but I figured out nothing was wrong with the combat system itself, since this simple script also had the same issue. This is the script:
local plr = game.Players.LocalPlayer
local character = plr.CharacterAdded:Wait()
script.Parent.Activated:Connect(function()
print("activated")
end)
In this script, it should print âactivatedâ upon clicking while the tool is equipped, but this simply doesnât work. I found the solution was to modify the script where instead of using âCharacterAdded:Wait()â it simply gets the character by âplr.Characterâ
local plr = game.Players.LocalPlayer
local character = plr.Character
script.Parent.Activated:Connect(function()
print("activated")
end)
I made this post because I felt that using âCharacterAdded:Wait()â was a much better approach to getting the character. Please let me know if this is the wrong category as this is my first post.
Hello, I 'm not a very experienced proggrammer, for me, the best option to use is plr.Character, but I think plr.CharacterAdded:Wait() works too, try if it works removing âlocalâ.
I tested the script by removing âlocalâ but the problem still occurs. The script only works when I do âlocal character = plr.Characterâ or âcharacter = plr.Characterâ Thanks for the help, but I am looking for a answer that explains why âPlr.CharacterAdded:Wait()â doesnât work.
The issue most likely was because plr.CharacterAdded:Wait() was yielding for the character being added, even though it was added already, which resulted in an infinite yield of the script. It works, but the issue is the function ran a little too late, so to be sure, always include plr.Character when fetching the character.