How can I make this more efficient?

Hey, so I’ve been thinking about making a recipe system for my portfolio such as in Frappe where you mix together ingredients in a cup to make different drinks. I’d say this is very easy to make but extremely time consuming for the way I would do it. If I were to make it there would be an incredible amount of if then statements like this:

script.Parent.Touched:Connect(function(hit)
	if hit.Parent.Name == "Cup" then
		hit.Parent.Name = "Milk"
	elseif hit.Parent.Name == "Coffee" then
		hit.Parent.Name = "Coffee with milk"
	elseif hit.Parent.Name == "Sugar" then
		hit.Parent.Name = "Sugary milk"
	end
end)

If there were a lot of recipes there would be a lot of elseif statements and I feel like this is extremely inefficient and there is a much better way to accomplish this. If somebody could help me that would be greatly appreciated. Thanks!

1 Like

If you are looking to add easy editing to the script and less lines then I’d use a table, loop through each component as see it’s result from there

local States = {
	["Cup"] = "Milk",
	["Coffee"] = "Coffee with milk",
	["Sugar"] = "Sugary milk",
}

script.Parent.Touched:Connect(function(hit)
	local result = States[hit.Parent.Name] or nil
	if result then
		hit.Parent.Name = result
	end
end)
4 Likes

For really complex recipes it might be useful to create some kind of dependency tree listing each possible recipe with its prerequisites. That way as the player mixes different things rather than relying on what name the cup has, they would be traversing through the tree structure for the script to track what state the mixture is at.

1 Like

I like this method because it looks a lot cleaner.