Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How come this script wont check if something exists?

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

✓ Accepted answer

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)

1 comment

0

you stole my question >:V

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)

This discussion is preserved as it was. New answers, comments, and votes are closed.