Failed to find the model with Self

I tried to make OOP base npc module by myself for the first time.. it doesn’t go quite well
the module failed to find said model even tho it is a basic r6 rig with PrimaryPart already set to HumanoidRootpart
image

my first poorly writen module:

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local SimplePath = require(ReplicatedStorage.Modules.SimplePath)

local Wanderer = {}

Wanderer.__index = Wanderer

function Wanderer.new(char:Model)
	local self = setmetatable({}, Wanderer)
	self.AI = char
	print(self.AI.ClassName)
	self.Cooldown = 5
	self.Health = 20
	self.Speed = 10
	
	local Hum = char:WaitForChild("Humanoid")
	Hum.WalkSpeed = self.Speed
	Hum.MaxHealth = self.Health
	Hum.Health = Hum.MaxHealth
	
	if self.AI.PrimaryPart ~= nil then
		self.AI.PrimaryPart:SetNetworkOwner(nil)
	end
	
	return self
end

function SelectNode(NodesFolder:Folder)
	return NodesFolder:GetChildren()[math.random(1, #NodesFolder:GetChildren())]
end

function Wanderer:Start()
	if self.AI.PrimaryPart == nil then return end
	local Target = SelectNode(workspace.PathNodes)
	local Path = SimplePath.new(self.AI)
	Path.Visualize = true
	Path.Blocked:Connect(function()
		Path:Run(Target)
	end)
	
	Path.WaypointReached:Connect(function()
		Path:Run(Target)
	end)

	Path.Error:Connect(function(errorType)
		Path:Run(Target)
	end)
	
	Path.Reached:Connect(function()
		task.wait(self.Cooldown)
		Wanderer:Start()
	end)

	Path:Run(Target)
end

return Wanderer

I use simple path for walking function

Test script

local WanderNPC = workspace.NPCs.Bob

local Module = require(game:GetService("ReplicatedStorage").Modules.WanderingNPC)
Module.new(WanderNPC)
Module:Start()

I tried setting the path directly to the model on workspace and it working normally
I’m still not fully understand how self work yet is there something important I need to know?

In your script, you’re calling Module.new(WanderNPC) but you never save the result. After that, you call Module:Start(), which means you’re calling Start on the module itself instead of on the instance you just created. Since the module doesn’t have an AI field, the code ends up trying to read PrimaryPart from a nil value, which causes the error you’re seeing.

To fix it, you simply need to store the instance returned by new and then call Start() on that instance. Here’s how it should look:

local WandererClass = require(ReplicatedStorage.Modules.WanderingNPC)
local wanderer = WandererClass.new(WanderNPC)
wanderer:Start()
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.