Right now, I’m trying to make a system that lets players repair generators. How can I write a system for all of the generators in just 1 main script, including when 2 or more are being interacted with?
I’ve already tried this a couple of times, but I’ve either created one that was too long, unorganized, buggy, or all 3. I have models ready with prompts to trigger them. I don’t want a script or anything, just hints to making a system myself. I would appreciate all kinds of help!
If you know your OOP you can probably handle it by using a component/class system, so you can have multiple items (generators) that do the same thing but instantiated and separate from one another, where you only need to define the behavior once
local Generator = {}
Generator.__index = Generator
function Generator.new(model)
local self = setmetatable({}, Generator)
self.model = model
self.repairingPlayers = {}
self.repairProgress = 0
return self
end
function Generator:startRepair(player)
if self.repairingPlayers[player.UserId] then
return -- Player is already repairing this generator
end
self.repairingPlayers[player.UserId] = true
coroutine.wrap(function()
while self.repairingPlayers[player.UserId] and self.repairProgress < 100 do
self.repairProgress = self.repairProgress + 1
self.model.Progress.Value = self.repairProgress
wait(1) -- Adjust repair speed here
end
if self.repairProgress >= 100 then
self:completeRepair()
end
end)()
end
function Generator:stopRepair(player)
self.repairingPlayers[player.UserId] = nil
end
function Generator:completeRepair()
self.repairProgress = 100
self.model.Progress.Value = self.repairProgress
-- Add any additional logic for a completed repair here
end
return Generator
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Players = game:GetService("Players")
local GeneratorModule = require(script.Parent:WaitForChild("GeneratorModule"))
local repairRemoteEvent = Instance.new("RemoteEvent", ReplicatedStorage)
repairRemoteEvent.Name = "RepairRemoteEvent"
local generators = {}
-- Create generator instances from models in workspace
for _, model in ipairs(workspace:GetChildren()) do
if model.Name == "GeneratorModel" then
local generator = GeneratorModule.new(model)
generators[model] = generator
end
end
repairRemoteEvent.OnServerEvent:Connect(function(player, action, generatorModel)
local generator = generators[generatorModel]
if action == "start" then
generator:startRepair(player)
elseif action == "stop" then
generator:stopRepair(player)
end
end)
Players.PlayerRemoving:Connect(function(player)
for _, generator in pairs(generators) do
generator:stopRepair(player)
end
end)