Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

why does this script only change parent of 1 tool why not all tools in backpack?

Asked by
MHaven1 159
8 years ago
01script.Parent.Touched:connect(function(hit)
02    local human = hit.Parent:FindFirstChild("Humanoid")
03    if human ~= nil then
04        print("Human Found!")
05        local player = game.Players:FindFirstChild(hit.Parent.Name)
06        if player ~= nil then
07            print("Player Found!")
08            local backpack = player:FindFirstChild("Backpack")
09            if backpack ~= nil then
10                print("Backpack Found!")
11                local alltools = backpack:GetChildren()
12                for i,v in pairs(alltools) do
13                    if v.ClassName == "Tool" then
14                        print("Tool Found!")
15                        if game.Workspace:FindFirstChild(hit.Parent.Name.. "'s BikePackback") == nil then
View all 26 lines...

i want this script to move all the stuff that are tools to a different model in workspace when they touch the brick but this script only moves 1 tool to that model not all of them. please help. i dont want this script to move things other then tools to the model in workspace. please help me

1 answer

Log in to vote
1
Answered by 8 years ago
Edited 8 years ago

The section of your current code with the problem, starting with your line 15.

1if game.Workspace:FindFirstChild(hit.Parent.Name.. "'s BikePackback") == nil then --if it doesn't exist
2    local model = Instance.new("Model") --make a new one
3    model.Name = hit.Parent.Name.. "'s BikePackback"
4    model.Parent = game.Workspace
5    v.Parent= model --and put the current tool in it
6end

The issue is that if the backpack does exist then you do nothing with the tool in the loop.

There are also a few other issues with your code. With what you are trying to do, it is much better to put the if statement after the loop for the tools, rather than inside it.

For generally cleaner code, it is better to make the bikepack a variable rather than trying to find it several times, since you'll need to use it several times. It is a better practice to use the :IsA() method rather than checking the name of the class, and there an optional second argument you can put in an Instance.new() call that lets you define the parent.

Here is a replacement for your lines 12-22.

01local pack = game.Workspace:FindFirstChild(hit.Parent.Name.. "'s BikePackback") --get the pack
02if pack == nil then --if it doesn't exist
03    pack = Instance.new("Model", workspace) --make a new one
04    model.Name = hit.Parent.Name.. "'s BikePackback"
05end
06for i, v in pairs(alltools) do --loop through tools
07    if v:IsA("Tool") then --make sure it's a tool
08        v.Parent= model --and parent the tool
09    end
10end

If you have any further questions, feel free to leave a comment.

Ad

Answer this question