Hello
I’m currently implementing the NPC system into my game, because I want to make the NPC behave like a single player, with minimal change to the current source code, so I want to create an NPC class that has same structure as Player class
I just want the NPC class to have a UserId field, a Character field and be able to trigger events like the Player class
Can someone help me?
Thank
Player
instance is its own userdata
and also has some inherited properties. The closest we can get is by creating table objects (prototype classes) with similar properties, states, behaviors.
In the lua VM we don’t have access to underlaying C code to create real userdata. That would overcomplicate things as well. It also wouldn’t make sense to deeply copy every single element, since NPCs don’t need properties and functions like :SetAccountAge()
, :GetFriendsOnline()
, .DevComputerMovementMode
and so on.
NPCs wouldn’t have a camera, therefore some functions player instances have would have to be slightly omitted, such as :Move(walkDirection: Vector3, relativeToCamera: boolean)
.
Other than that, it’s not complicated. Take the draft I’m sending as a possible example.
local Npc = {}
Npc.__index = Npc
local CharacterModule = require(...)
local signals = {}
local function Init(self)
self.Character = CharacterModule.new() -- suppose this returns prepared char
signals[self.UserId]:Fire(self.Character)
-- configure everything else
-- ...
end
function Npc.new(uniqueID: number)
local self = setmetatable({}, Npc)
self.UserId = uniqueID
self.ClassName = "NPC"
self.DisplayName = "Dummy"
self.Character = nil
signals[self.UserId] = {}
signals[self.UserId].CharacterAdded = Instance.new("BindableEvent")
-- Shotcut, so the requiring script can use :Connect(), :Wait() etc.
self.CharacterAdded = signals[self.UserId].CharacterAdded.Event
Init(self)
return self
end
function Npc:Move(walkDirection: Vector3)
local humanoid = self.Character:FindFirstChild("Humanoid")
humanoid:WalkToPoint(walkDirection)
end
function Npc:Destroy()
signals[self.UserId] = nil
self.Character:Destroy()
self.Character = nil
end
return Npc
Technically, you could also take Instance
class into consideration, and have the Npc class inherit some of the functionality, though that doesn’t seem very necessary.
This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.