local ReplicatedStorage = game:GetService("ReplicatedStorage")
local ServerStorage = game:GetService("ServerStorage")
local function GetRandomMob()
local MobsFolder = ServerStorage:WaitForChild("Mobs"):GetChildren()
local randomItem = MobsFolder[math.random(1, #MobsFolder)]
return randomItem
end
local viewDistance = 20
local attackDistance = 5
local Mobs = {}
Mobs.__index = Mobs
function Mobs:Attack()
print(self.Mob)
end
function Mobs:Chase(mob,mobRP)
self.Mob = mob
self.HumRP = mobRP
local possiblePlayers = game:GetService("Players"):GetPlayers()
local target = nil
local distance = nil
local direction = nil
for i, player in pairs(possiblePlayers) do
local character = player.Character
if character then
local distanceVector = (character.HumanoidRootPart.Position - self.HumRP.Position)
if not target then
target = player
distance = distanceVector.Magnitude
direction = distanceVector.Unit
elseif distanceVector.Magnitude < distance then
target = player
distance = distanceVector.Magnitude
direction = distanceVector.Unit
end
end
end
if target then
if distance <= viewDistance and distance >= attackDistance then
mob.Humanoid:Move(direction)
else
mob.Humanoid:Move(Vector3.new())
end
end
end
function Mobs.new(spawnPart, Health, Damage, Speed, Cooldown)
local mobTemplate = setmetatable({}, Mobs)
local clone = GetRandomMob():Clone()
local cloneHum = clone:WaitForChild("Humanoid")
mobTemplate.Health = Health
mobTemplate.Damage = Damage
mobTemplate.Speed = Speed
mobTemplate.Cooldown = Cooldown
mobTemplate.Mob = clone
mobTemplate.HumRP = clone:WaitForChild("HumanoidRootPart")
cloneHum.Health = Health
cloneHum.WalkSpeed = Speed
clone:SetPrimaryPartCFrame(CFrame.new(spawnPart.CFrame.Position))
clone.Parent = workspace.Main.Mobs
return mobTemplate
end
return Mobs
repeat wait() until game.Players.PlayerAdded
local Mobs = require(script:WaitForChild("Mobs"))
local GeneratedRooms = workspace.Main:WaitForChild("GeneratedRooms"):GetChildren()
local RunService = game:GetService("RunService")
local spawnParts = GeneratedRooms.SpawnParts
for i, Room in pairs(GeneratedRooms) do
for i, spawnPart in pairs(Room.SpawnParts:GetChildren()) do
local Mob = Mobs.new(spawnPart,100,10,12,3)
RunService.Heartbeat:Connect(function()
if Mob then
Mobs:Chase(Mob,Mob.HumanoidRootPart)
end
end)
end
end
currently learning OOP and trying to make attacking npcs with it, running into a problem where its saying that the npcs humanoidrootpart is nil ( attempt to index nil with position <---- nil = humanoidrootpart ). the humanoidrootpart is defined i made sure of that so i dont know whats happening, it prints and everything
the system is supposed to get a random npc from a folder, clone it into an open position (a part i have laid out) and then the npc should chase after the player