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

How to randomize SurfaceGUI into different part?

Asked by 3 years ago

I'm trying to create a board with nine squares. Every space includes a surfacegui that is independently controlled by a physical button. My main goal would be to create a button that will take all nine surfaceGUIs and shuffle them randomly in a different square. How would I execute this without any surfaceGUI placing itself in the same square as another?

1 answer

Log in to vote
0
Answered by
TGazza 1336 Moderation Voter
3 years ago
--// this ColorGuis Variable is a table of the physical parts that contain screenguis
local ColorsGuis  = script.Parent.Parent.ColorGuis:GetChildren()

--// a screengui button, can use a physical ClickDetector or even touch to trigger this
--// just change this to your button and the event appropriately
local RandomButton = script.Parent.SurfaceGui.TextButton

--// random button hookup!
RandomButton.MouseButton1Click:Connect(function(blah) 
    local TabCopy = (function() --// Record and copy the original table containing The guis 
        local T = {} 
        for k,v in pairs(ColorsGuis) do 
            T[k] = v 
        end 
        return T 
    end)()
    local Guis = (function() --// Store the guis in a table and remove them from the game...
        local Tab = {} 
        for _,Gui in pairs(ColorsGuis) do 
            Tab[#Tab+1] = Gui.SurfaceGui 
            Gui.SurfaceGui.Parent = nil  -- This bit is optional, remove this is you don't like the idea of your guis dissapearing then reappearing..
        end 
        return Tab  
    end)()
    wait(1) -- wait a second (Optional!)
    --// now the meat of the function, randomizing the guis back into the gui parts
    --// cycle through the gui parts    
    for _,Gui in pairs(ColorsGuis) do
        --// select a random part from our copied table
        local Rnd = math.random(1,#TabCopy)

        --// select a random Gui 
        local SelectedGui = math.random(1,#Guis)

        --// Set this Gui parent to the selected Gui Part
        Guis[SelectedGui].Parent = Gui


        --// remove the Selected Physical Part from our copy and remove the selected Gui from our Gui table so we dont select it again!
        table.remove(TabCopy,Rnd)
        table.remove(Guis,SelectedGui)
    end
    --// Done!
end)

Should work if hooked up correctly, Hope I've left meaningful comments explaining what does what. If not let me know!

Ad

Answer this question