The script doesn't reload itself after adding a player to an array

Well, I’ll try to explain as much as I can :sweat_smile:

I have a script that positions the camera in the middle of two players’ positions (specifically, the HumanoidRootParts of them). So I try to add the humRPs of the players to an array so I can reference them. It works, but only for the player2.

I believe when Player1 is connected to the server, player2 isn’t. So I think that’s where the problem is addressed. :thinking:

But I don’t know how to resolve this…

local runService = game:GetService("RunService") 
local camera = workspace.Camera

for i, v in pairs(game.Players:GetPlayers()) do
	local character = v.Character or v.CharacterAdded:Wait()
	local humanoidRootPart = character:WaitForChild("HumanoidRootPart")
	table.insert(roots, humanoidRootPart)
end

	
runService.RenderStepped:Connect(function()	
	
	if roots[2] and roots[1] then
	
	local between = (roots[1].Position + roots[2].Position)/2

	camera.CFrame = CFrame.new(Vector3.new(between.X, between.Y + 1, between.Z + 10))
	
	else 
		return
	end
end)

-Player 2

1 Like

Use Players.ChildAdded to detect for when the 2nd player that joins. When they join get their HRP and put it inside your table

I’m not sure if PlayerAdded works on the client so that’s why I didn’t use it

Players.PlayerAdded does work on the client, and I believe your correct in that being the solution here. They could do a Players.PlayerAdded:Wait() [assuming there will only be 2 players per server] to wait until the second player is added, but they’d also have to make sure that they didn’t already get the second player into their array. As that would result in a infinite wait since a third player would never join to end the :Wait()

I really don’t understand how to use what you’re saying :sweat_smile:

in this space here I would add this code:

for i, v in pairs(game.Players:GetPlayers()) do
	local character = v.Character or v.CharacterAdded:Wait()
	local humanoidRootPart = character:WaitForChild("HumanoidRootPart")
	table.insert(roots, humanoidRootPart)
end

-- added code
if #roots == 1 then -- (if there is only one root in the array)
	-- this means that we loaded in first, we need to wait for the
	-- other player!

	-- this will stall until a new player is added,
	-- NewPlayer will be set to the player who joined.
	local NewPlayer = game.Players.PlayerAdded:Wait()
	
	local character = NewPlayer.Character or NewPlayer.CharacterAdded:Wait()
	local humanoidRootPart = character:WaitForChild("HumanoidRootPart")
	table.insert(roots, humanoidRootPart)
end
-- end of added code

runService.RenderStepped:Connect(function()	

added comments that explain what it does

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.