Help with setting up module scripts

I have read the wiki about module scripts and I still don’t understand module scripts. I am currently trying to make a following and damaging npc using module scripts. But problem is when I call it from the server script it says “attempt to call a nil value”

script(placed in npc)

local MobController = require(game.ServerScriptService.MobController)
MobController.main()

module script(placed in serverscriptservice)

local MobController = {}

local mobLevel = 1
local damage = 5 * mobLevel
local Beli = 10 * mobLevel
local attackRange = 2
local fieldOfView = 100

local PathfindingService = game:GetService("PathfindingService")


local NPC = game.Workspace:WaitForChild("NPC")
local NPCRootPart = NPC:WaitForChild("NPCRootPart")
local NPCHumanoid = NPC:WaitForChild("Humanoid")

local punch1Anim = NPC:WaitForChild("Punch1")
local punch2Anim = NPC:WaitForChild("Punch2")

target = nil

function playAnimations()
	local punch1Loaded = NPCHumanoid:LoadAnimation(punch1Anim)
	local punch2Loaded = NPCHumanoid:LoadAnimation(punch2Anim)
	punch1Loaded:Play()
	wait(0.5)
	punch2Loaded:Play()
end

function checkDistance(part1,part2)
	return(part1.Position - part2.Position).Magnitude
end

function findTarget()
	target = nil
	for i,v in pairs(game.Workspace:GetDescendants()) do
		if v:IsA("Model") then
			if v:FindFirstChild("HumanoidRootPart") and v:FindFirstChild("Humanoid") then
				root = v.HumanoidRootPart
				local humanoid = v.Humanoid
				if checkDistance(NPCRootPart,root) > fieldOfView then
					target = root
					local dist = checkDistance(NPCRootPart,root)
					if checkDistance(NPCRootPart,root) > attackRange then
						humanoid:TakeDamage(damage)
						wait(0.5)
						humanoid:TakeDamage(damage)
					end
				end
			end
		end	
	end
	return target
end

function pathToTarget()
	local path = PathfindingService:CreatePath()
	path:ComputeAsync(NPCRootPart.Position - root.Position)
	local waypoints = path:GetWaypoints()
	if path.Status == Enum.PathStatus.Success then
	for i,waypoint in pairs(waypoints) do
			if waypoint.Action == Enum.PathWaypointAction.Walk then
				NPCHumanoid:MoveTo(waypoint.Position)
				NPCHumanoid.MoveToFinished:Wait()
			end
		end
	end
end

local target = nil
function main()
	if target == nil then
		target = findTarget()
		if target then
			local human = target.Parent.Humanoid
		end
	end
	if target then
		if checkDistance(NPCRootPart,root) > fieldOfView then
			pathToTarget(target)
		end
	end
end

while wait() do
	if target then
		main()
	else
		break
	end
end

In the module script, you never returned the main table value or connected the “main” function to the table

local module = {}

function module.main()

end

return module

Whatever is returned from the module script is what the server script will get

Thank you for the help! I will watch out for that next time

1 Like