I have a farm game project. And it has a crop system in it. My Server-Sided script is checking all crops in the field with RunService RenderStepped. Adds an amount to crops grown value, checks if it needs water, checks if its full-grown, etc (40 times a second i guess). Is there any better way to do this? Would it lag my game or just fine?
Here is an example:
RunService.Heartbeat:Connect(function(dt)
for i, crop in pairs(Field) do -- Field is a table which stores all crop tables
if crop.Grown >= 10 then
crop.Grown = 10
print("I'm done")
else
crop.Grown += 1/40 -- Grow a bit
end
if crop.Water < 1 then
print("I need water!")
else
crop.Water -= 1/100 -- Get thirsty a bit
end
end
end)
I wanted to ask before starting to develop the whole script
You must ask yourself, do the crops in my field really need to be updated every heartbeat? I think this is a bit extreme, and while it could work fine with a small number of crops this can quickly become very inefficient.
Simply use a while loop and check every crop every X seconds or so, and maybe randomise the amount of “Grown” they need to finish growing, so they don’t all grow at exactly the same time.
How about you create an event for each crop. Whenever the crop grows, fire the event.
Then, you can loop over each crop and hook their events once, and then detect whenever they grow and what action to take.
When a new crop is added, which you can detect either by creating another event “AddCrop” or detecting via ChildAdded, you can hook that crop as well.
When a crop is removed, the evenr should be deleted and as a result all connections should be destroyed on their own, no further intervention.