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.
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)
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()
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()