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!
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.