Rewriting code for a vehicle system

Hello! I am planning to rewrite my vehicles systems code but I want to know the best way I should do this!

I want to have a module script in ServerStorage that’ll handle doors, lights, horns and other features.

Currently there’s functions that handle these but all these functions have an argument that it for the vehicle.

e.g:

function Horn(Vehicle)
    Vehicle.HornSound:Play()
end

Is there a way to lose the vehicle argument and apply these functions to the vehicle models instead of making random functions find the vehicle when it gets called?

Any other tips to be cleaner and optimized are appreciated!

If anyone has any templates of examples on the best and optimized way to write code let me know!

Thanks!

1 Like

Look into OOP and ECS, they are the most suited for this:

How it would look with OOP:

local vehicle = Vehicle.new(...)
vehicle:Drive(toPosition: Vector3)
vehicle:PlayRadio(songId: string?)
vehicle:Horn()

As for ECS, its a bit more complex and easy to mess up for beginners. Also, you would need to use an external library preferably matter.

To extend you could do something along the lines like this as a module.

local Car = {}
Car.__index = Car

export type Types = {
    Car : Model,
    Horn : Sound
}

function Car.new(Props : Types)
    local self = setmetatable({},Car)
    self.Car = Props.Car:Clone()
    self.Horn = Props.Horn
    self.Speed = 100
    self.Brake = 50 -- you could set this and above as a property after defining the new class, or include another argument.
    self.Car.Parent = workspace

    return self
end

function Car:Horn()
    self.Horn:Play()
end

return Car

Then when creating a new Car class in another script:

local CarClass = require(game.ServerStorage.Car)

local Car = CarClass.new({Car = workspace.Car, Horn = workspace.Car.Horn})
Car.Speed = 70
Car.Brake = 40 -- changing the specific properties of the class

Car:Horn() -- Horn is a static function of the Class, meaning it is relative to that only.

Thanks!

Should i have a module script inside of replicated storage that controls both client and server code or have 2 separate modules?

Have 2 separate modules

Alright, how should i program it? Between the 2 modules on client and server scripts?

Do i have client scripts fire remote events that call the module functions?

Should i do the metatables thing on both module scripts?