Hello Developers!
I created a NPC which is called: "Sad Ninja". Anyway, the NPC has a Pathfinding script which will activate once someone damages the NPC. The Issue however is that the NPC Pathfinding script is buggy, let me explain. When the NPC is chasing a player, the NPC will usually briefly stop in place which makes the NPC looks like it's lagging
Script:
01 | --//NPC\\-- |
02 | local NPC = script.Parent |
03 | local Humanoid = NPC.Humanoid |
04 | local OldHealth = Humanoid.Health |
05 | --//Services\\-- |
06 | local RunService = game:GetService( "RunService" ) |
07 | local Pathfinding = game:GetService( "PathfindingService" ) |
08 | local Players = game:GetService( "Players" ) |
09 | --//Functions\\-- |
10 | local function Jump() |
11 | Humanoid.Jump = true |
12 | end |
13 | local function FindNearestPlayer() |
14 | local RadiusToFindUser = 500 |
15 | local Target = nil |
It's more likely because of Network Ownership. By default, all parts except the players' limbs are owned by the Server. Anchored parts are always owned by the Server, while unanchored parts are not. If a player's character gets near an unanchored part, the game engine will automatically set its network ownership to the player's client. That might cause a problem to the part.
If a part's network owner is not the Server and is one of the clients, it can cause lag to the part if the network owner is lagging. To the network owner, the client, it seems that it is just doing fine, it is not lagging; but to the other clients with better connection and the Server, it is lagging.
And that could be why you're Ninja NPC is buggy. The network owner of the NPC's limbs is the target player being chased. To fix that, we will set every limb of the NPC, every accessory (if they have one), and tool handles (if they have one) network ownership to the Server using BasePart:SetNetworkOwner(nil)
.
Just simply attach this to the end of your code and it should solve it.
01 | while true do -- we will loop this to detect if network ownership changes |
02 | for _, descendant in ipairs (NPC:GetDescendants()) do -- we will iterate every descendant of the NPC |
03 | if descendant:IsA( "BasePart" ) then -- if descendant is a part |
04 | if descendant:GetNetworkOwner() ~ = nil then -- if network owner is not the Server |
05 | descendant:SetNetworkOwner( nil ) -- sets network ownership to the Server |
06 | end |
07 | end |
08 | end |
09 |
10 | task.wait() -- in case if the for loop above didn't yield/was super fast, we will add a yielding (waiting/delaying) function in the while loop to avoid script timeout (script timeouts can lag your game or worse, break your game; script timeouts happen when loops don't yield and is going super duper fast, almost 0 seconds of yield before repeating) |
11 | end |