Code not running

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

There is also no console output.

Why is it not running, and how do I make it run?

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.

The script doesn’t load before players join the game. It is activated through a remote event.

And if you mentioned how:

Does that mean there is a working method as an alternative to numbers?

Can you make sure that the remote is fired, so the script runs?

I know the script runs because there is code before it that works when the remote is fired.

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.

if nplrs > 0 then
print("Works")

I added a print here and it printed.

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.

Did “print(RPC)” and “print(Num)” works too?

They do not work when I run the script.

This did not fix the issue either.

I think I found the invisible error, in your “print(RPC)”, you are printing an instance, try doing “print(RPC.Name)”.

Any errors in the output? Trying your code in an r6 dummy shows some errors.

I think I fixed your 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