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

How come this script wont check if something exists?

Asked by 8 years ago
function loadTruck()
    if game.Workspace["Army Truck 4"] then
        game.Workspace["Army Truck 4"]:Destroy()
        local clone = game.Lighting["Army Truck 4"]:Clone()
        clone.Parent = game.Workspace
    else
        local clone = game.Lighting["Army Truck 4"]:Clone()
        clone.Parent = game.Workspace
    end
end

script.Parent.ClickDetector.MouseClick:connect(loadTruck)

Error:

13:50:28.155 - Army Truck 4 is not a valid member of Workspace; 13:50:28.156 - Script 'Workspace.Model.Part.Script', Line 2

It's supposed to delete the Army Truck if it already exists, and spawn a new one. And if one doesn't exist, it should spawn one.

2 answers

Log in to vote
2
Answered by
Pyrondon 2089 Game Jam Winner Moderation Voter Community Moderator
8 years ago

You need to use FindFirstChild on Line 2.

function loadTruck()
    if game.Workspace:FindFirstChild("Army Truck 4") then
        game.Workspace["Army Truck 4"]:Destroy()
        local clone = game.Lighting["Army Truck 4"]:Clone()
        clone.Parent = game.Workspace
    else
        local clone = game.Lighting["Army Truck 4"]:Clone()
        clone.Parent = game.Workspace
    end
end

script.Parent.ClickDetector.MouseClick:connect(loadTruck)

0
you stole my question >:V koolkid8099 705 — 8y
Ad
Log in to vote
1
Answered by 8 years ago

So basically you had your conditions wrong. Whenever your trying to return a Boolean for an exsisting instance, you should use the :FindFirstChild() method. This allows you to return a Boolean for whether the part exists or not. Here how your script should look:

script.Parent.ClickDetector.MouseClick:connect(function(click)
    if not game.Workspace:FindFirstChild("Army Truck 4") then
        local clone = game:GetService("Lighting")["Army Truck 4"]:Clone()
        clone.Parent = game.Workspace
        end
        if game.Workspace:FindFirstChild("Army Truck 4") then

        game.Workspace["Army Truck 4"]:Destroy()
        local clone = game:GetService("Lighting")["Army Truck 4"]:Clone()
        clone.Parent = game.Workspace

    end
end)

Answer this question