Search code examples
for-loopluaroblox

Why does my Roblox for loop not work? Doesn't print all outputs


So I am making a CameraScript on roblox studio that when the player touches a robot, the camera focuses on the robot. But the for loop seems to not work though.

The script in game.StarterPlayer.StarterPlayerScripts:

workspace.CurrentCamera.CameraType = Enum.CameraType.Scriptable

game.Players.LocalPlayer.CharacterAdded:Connect(function(char)
    local g = char.Name
    print(g) --Just for debugging purposes
    print("Player Loaded!")
    
    tou(char)
end)

function tou(char)
    print("Function had ran")
    for _,p in pairs(char:GetChildren()) do
        print("We're here loopin ur parts...")
        p.Touched:Connect(function(hit)
            print("Someone touched?")
            if hit.Parent.Name == "Robot" and hit.Parent:IsA("Model") then
                print("It's the robot!")
                workspace.CurrentCamera.CFrame = hit.Parent.Look.CFrame
                workspace.CurrentCamera.Focus = hit.Parent.Head.CFrame
                print("Camlock should be successfull...")
            else
                print("That ain't a robot tho...")
            end
        end)
    end
end

This is the piece of code that doesn't work:

for _,p in pairs(char:GetChildren()) do
    print("We're here loopin ur parts...")
    p.Touched:Connect(function(hit)
        print("Someone touched?")
        if hit.Parent.Name == "Robot" and hit.Parent:IsA("Model") then
            print("It's the robot!")
            workspace.CurrentCamera.CFrame = hit.Parent.Look.CFrame
            workspace.CurrentCamera.Focus = hit.Parent.Head.CFrame
            print("Camlock should be successfull...")
        else
            print("That ain't a robot tho...")
        end
    end)
end

I tried putting the for loop inside directly the CharacterAdded event, putting print() for debugging but it only printed these:

17:55:24.242  <username>  -  Client - CamLockOnKill:5
17:55:24.243  Player Loaded!  -  Client - CamLockOnKill:6
17:55:24.243  Function had ran  -  Client - CamLockOnKill:12

...but it didn't print the others.


Solution

  • It doesn't print We're here loopin ur parts... so the loop isn't run.

    The only way to not run a generic for loop like

    for _,p in pairs(char:GetChildren()) do
    end
    

    without errors is to provide an empty table to pairs.

    So char does not have any children. Find out why you think it has children and why it does not.