Hi all. I’ve determined that I would like to try to use an object-oriented approach for the game I’m developing, which involves NPCs that are capable of fighting both other NPCs and players. A useful object for such a game to have would therefore be an NPC, as I would like to have many instances of different kinds of NPCs that each have their own independent set of data and behavior.
I have read about OOP here and believe that I understand what it is saying. However, I am confused as to how to proceed from where it leaves off.
In particular, here is a section of the tutorial:
--module script called Car in game.ReplicatedStorage
Car = {}
Car.__index = Car
function Car.new(position, driver, model)
local newcar = {}
setmetatable(newcar, Car)
newcar.Position = position
newcar.Driver = driver
newcar.Model = model
return newcar
end
function Car:Boost()
self.Speed = self.Speed + 5
end
return Car
--main script
Car = require(game.ReplicatedStorage.Car)
newcar = Car.new(Vector3.new(1,0,1), "Guest1892", game.ReplicatedStorage.F1Car)
newcar:Boost()
My confusion lies with how to use the above to actually generate, for example, an F1 car in the physical game world, which is not explained in the tutorial.
If I were creating, for example, a Part to put in the game world, I could do something like
newpart = Instance.new("Part")
newpart.Size = Vector3.new(2,2,4)
newpart.Position = Vector3.new(1,0,1)
newpart.Parent = game.Workspace
which would, of course, result in a part of size 2x2x4 appearing at position (1,0,1) in the game. How do I do this for the car, though? newcar
is not an Instance
; rather, it is a table with some values; as such, doing something like newcar.Parent = game.Workspace
would not yield the desired effect. The “Instance
-like” component of newcar
is the model F1Car
contained in ReplicatedStorage
. As such, doing something like
newcar = Car.new(game.ReplicatedStorage.F1Car:Clone(), "Guest1892", Vector3.new(1,0,1))
newcar.Model.Parent = game.Workspace
does result in the model appearing in the game, but this doesn’t seem to me to be the correct procedure to use, since the newcar
table (or at least parts of it) appears to now be redundant; (1,0,1) for example, doesn’t actually represent the position of the car in the game – to achieve that, I would need to change the position of the model itself to be (1,0,1), and now I’ve got two copies of this position.
I suppose my overarching point is this: with Instance.new()
, there seems to be an intuitive relationship between the creation and manipulation of the object and the physical representation of that object ingame. However, I don’t see how to achieve this relationship with the kinds of custom-made objects and constructor functions as described in the tutorial. I’m sure this is just a result of my poor understanding of the topic at hand, so any and all relevant pointers would be appreciated.