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

How To Make This Function More Efficient? (Inventory Gui)

Asked by 7 years ago

I have a GUI that moves a frame to allow the user to drop an amount of wood. It seems to work fine but I want the user to be able to do the same thing with stone, metal, and other items in the inventory. This is the function to open the drop wood menu:

tiles.Wood.SlideSpace.WoodDrop.MouseButton1Down:connect(function()
    if script.Parent.Position.X.Scale ~= 1 then 
        script.Parent.DropText.Text = "Drop Wood"
        script.Parent:TweenPosition(UDim2.new(1,6,0,50) , "In" , "Sine" , .5 , false)
    else 
        print("Cannot Execute")
    end
end)

I know that there is a better way to do this for other items like stone instead of retyping the entire function and just changing the word Wood to Stone. Would anyone be able to help with this?

Thank you, Boogieboon

1 answer

Log in to vote
0
Answered by 7 years ago
Edited 7 years ago

In your case as they all do the same thing but with different data you can use one function and pass this data. This will also stop code duplication and helps in other areas such as debugging or maintenance.

Example:-

-- the same code as above 
local function dropItem(itm, dropName) -- We will use the paramaters passed 
    if itm.Position.X.Scale ~= 1 then       
        -- is the drop text in each item?
        itm.dropTxt.Text  = dropName
        -- I would prefer if you used Enums 
        itm:TweenPosition(UDim2.new(1,6,0,50) , "In" , "Sine" , .5 , false)
    else
        print("Cannot Execute")

    end
end

-- connecting the items

-- It would be best to use a loop but I do not know how your GUI is setup
local woodDrop = tiles.Wood.SlideSpace.WoodDrop

woodDrop.MouseButton1Down:Connect(function()
    -- we now run out funcion above
    dropItem(woodDrop, 'Drop Wood') -- run the function with the given data
end)

This is just a basic example of how this can be done you may need to change it to fit your needs.

I hope this helps.

Ad

Answer this question