I'm trying to loop a i,v statement to check workspace if a certain item is there. I have a while true do loop activating when I press a button, but it doesn't work on the new instances being added to the workspace. Here's what I currently have.
local character = game.Players.LocalPlayer.Character local hum = character.HumanoidRootPart local work = game.Workspace:GetChildren() while valuee == true do -- this code is in a function wait(1) for i,v in pairs(work) do if v.Name == "Test" then v.CFrame = work.Part.CFrame end if valuee == false then break end end end
Hello,
It appears that you're i, v statement is fine, but you are incorrectly referencing objects from your "work" table.
Instead of writing:
v.CFrame = work.Part.CFrame
write:
v.CFrame = workspace.Part.CFrame
this is because the :GetChildren()
function returns a table value, which means that to access its objects, we must use a different method OR simply reference "Part" through the workspace.
To add, your code could be refined in many areas, as annotated below:
local player = game:GetService("Players").LocalPlayer -- more common way to get the local player workspace:WaitForChild(player.Name) -- wait for character object to be created, often the player's client connects to the server before the server can create their respective character local character = game.Players.LocalPlayer.Character local hum = character.HumanoidRootPart while valuee == true do -- this code is in a function wait(1) for i,v in pairs(workspace:GetChildren()) do -- this way each loop, the table stays true to the current amount of objects in the workspace. if we define the list before the while true loop, other objects could be added to the workspace without getting searched. This also helps clean the code by removing excess variables if v.Name == "Test" then v.CFrame = workspace.Part.CFrame --search workspace for part end if valuee == false then break end end end
I hope this answer helped you!
Cheers, Ninjamanchase