Run click function on object that doesn't exist yet?

This is what I’m trying to do. After a player clicks GUI Object 1, Object 2 gets created. When object 2 gets clicked, object 2 gets destroyed. Then they can click object 1 to create 2, then click 2 to destroy 2. (AND they can repeat this) But if i have a function that runs when object 2 is clicked, i get an error because object 2 isn’t created yet.

How would I only check the for a click on object2 while object 2 is existent? so that i dont get an error.
Here are some things i tried.

script.Parent.MouseButton1Click:Connect(function()
     if Variable == 0 then
        TheFrame = Instance.new("Frame")
		TheFrame.Visible = true
		TheFrame.Name = Variable2
		TheFrame.Parent = script.Parent.Parent.Parent.Parent.Parent.Parent.Parent.settingsFrame.Images.ImagesAgain

	    TheImage = Instance.new ("ImageButton")
		TheImage.Name = ("TheImages")
		TheImage.Parent = TheFrame
		Variable = 1
     end
end)

TheImage.MouseButton1Click:Connect(function()
	script.Parent.Active = true
	script.Parent.ImageTransparency = 0
	script.Parent.Selectable = true
	for i,v in pairs (TheFrame:GetChildren())do
			if v.Name == ("TheImages")then	
				v:Destroy()
			end
	end
	TheFrame:Destroy()
	Variable = 0
end)

I’ve tried scripting the path to TheImage, and adding a WaitForChild, but it only works once. I did FindFirstChild, but it still says im trying to index a nil value. Please help.

maybe you can try using connection/connection:Disconnect().

local TheImage
local Variable2
local Connection = nil

script.Parent.MouseButton1Click:Connect(function()
     if Variable == 0 then
        TheFrame = Instance.new("Frame")
		TheFrame.Visible = true
		TheFrame.Name = Variable2
		TheFrame.Parent = script.Parent.Parent.Parent.Parent.Parent.Parent.Parent.settingsFrame.Images.ImagesAgain

	    TheImage = Instance.new ("ImageButton")
		TheImage.Name = ("TheImages")
		TheImage.Parent = TheFrame
		Variable = 1
		
		Connection = TheImage.MouseButton1Click:Connect(function()
			script.Parent.Active = true
			script.Parent.ImageTransparency = 0
			script.Parent.Selectable = true
			for i,v in pairs (TheFrame:GetChildren())do
				if v.Name == ("TheImages")then	
					v:Destroy()
				end
			end
			TheFrame:Destroy()
			Variable = 0
			Connection:Disconnect()
			Connection = nil
		end)
    end
end)
1 Like

Thanks for the reply! I tried it out and it seems to work so far.
What is happening when you put a click connect function inside of another? is the first click function waiting for the second? I thought that if you did that, the first function would run and then skip the second one because that click didn’t happen?

Idk the details really. It’s just something I’ve learned to use. Maybe someone else can explain it.

btw, you might want to add a check to prevent it from trying to make multiple connects with the Connection Variable and erroring

script.Parent.MouseButton1Click:Connect(function()
    if Connection ~= nil then return end