Script not recognizing child?

I made a regen button which regenerates the child of a script every 60 seconds or whenever a button is pressed. However the script displays this error on line 3:

Box is not a valid member of Script "Workspace.Regen Button.Regen"  -  Server - Regen:4
Here's the script
model = script.Box

backup = model:clone()
enabled = true

function regenerate()
	model:remove()

	wait(3)--

	model = backup:clone()
	model.Parent = game.Workspace
	model:makeJoints()

	script.Disabled = true
	script.Parent.BrickColor = BrickColor.new(26)--Black
	wait(3)
	script.Parent.BrickColor = BrickColor.new(104)--Purple
	script.Disabled = false
end

function onHit(hit)
	if (hit.Parent:FindFirstChild("Humanoid") ~= nil) and enabled then
		regenerate()
	end
end

script.Parent.Touched:connect(onHit)

while wait(60) do
	regenerate()
end

And this is the hierarchy in the Workspace:

image

What can I do to make it so that the script recognizes “Box” within itself so that the rest of the script functions as normal?

(Note: the box is unanchored however does not disappear from the workspace at the beginning of the simulation/test)

1 Like

Try this:

local model = script:WaitForChild("Box")
local enabled = true

function regenerate()
    local save = model:Clone()
	model:Destroy()
    model = save
    save = nil
	task.wait(3)
	makeJoints(model)
	model.Parent = workspace

    enabled = false
	script.Parent.BrickColor = BrickColor.new(26)--Black
	task.wait(3)
	script.Parent.BrickColor = BrickColor.new(104)--Purple
    enabled = true
end

function activate(hit)
	if (hit:IsA("Player") or hit.Parent:FindFirstChild("Humanoid")) and enabled then
		regenerate()
	end
end

function makeJoints(model)
    if not model:IsA("Model") then return end
    for _, part in model:GetDescendants() do
        if part:IsA("BasePart") then
            for _, connection in part:GetConnectedParts() do
                if connection:IsA("BasePart") then
                    local weld = Instance.new("WeldConstraint")
                    weld.Part0 = part
                    weld.Part1 = connection
                    weld.Parent = part
                end
            end
        end
    end
end

script.Parent.Touched:Connect(activate)
local click = Instance.new("ClickDetector")
click.Name = "Click"
click.Parent = script.Parent
click.MouseClick:Connect(activate)

local elapsed = 0
game:GetService("RunService").Heartbeat:Connect(function(delta)
    elapsed = math.clamp(elapsed + delta, 0, 60)
    if elapsed ~= 60 then return end
    elapsed = 0
    regenerate()
end)
2 Likes

The problem is that a variable does not create a copy of the model. And when you destroy the model, the variable is set to nil. You will need to create a separate instance (preferably in replicated storage) and clone that whenever you want to respawn the box

1 Like

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