I have code in a script inside of an NPC, but that code does not run when activated, despite the fact that every piece of code before this code runs appropriately.
The script is a ServerScript.
This is the code that does not work:
local Num = 0
repeat
local Players = game.Players:GetPlayers()
local nplrs = #Players
local Randomplayer = nil
if nplrs > 0 then
Randomplayer = Players[math.random(1, nplrs)]
local RPC = game.Workspace:WaitForChild(Randomplayer)
print(RPC)
local ClonePart = script.Parent["Left Arm"].Part:Clone()
ClonePart.Parent = workspace
ClonePart.Position = RPC:WaitForChild("Torso").Position
script.Parent.Sound:Play()
Num = Num + 1
print(Num)
wait(0.183)
end
until Num == 5
-- Npc rig is R6
In the line 7, you are searching for a “Random Player” but you are trying to find a Player with a number, same in the line 8, you are trying to find a player with a number and not a string.
However the problem is: The script loads before a player can join the game, so add a 5 seconds wait in the top of the code and test it.
I was wrong, since you don’t get an error in your console then everything is fine, try adding a print in the top of the line 7, inside “if nplrs > 0 then” and see if it prints.
Maybe try, repeat task.wait() or repeat wait(). But I suggest using task.wait() instead of wait() since it’s better. You can replace your wait() with task.wait() in the script.
repeat task.wait(1)
local Players = game.Players:GetPlayers()
local nplrs = #Players
local Randomplayer = nil
if nplrs > 0 then
Randomplayer = Players[math.random(1, nplrs)]
local RPC = game.Players:FindFirstChild(Randomplayer.Name)
local ClonePart = script.Parent:FindFirstChild("Left Arm"):Clone()
ClonePart.Parent = workspace
repeat task.wait() until RPC.Character
ClonePart.Position = RPC.Character:FindFirstChild("Torso").Position
script.Parent.Sound:Play()
Num = Num + 1
task.wait(0.183)
end
until Num == 5