#npc system
1 messages · Page 1 of 1 (latest)
mmm, that's good, so Ig I'll plan a clear plan for you
done!
You've 2 steps !
** # Step 1: NPC follows a player**
- Use Humanoid:MoveTo() or PathfindingService to make NPC move toward player’s character.
- Update target position frequently.
# Step 2: Player can buy NPC followers
**- Keep a value tracking how many NPCs the player owns.
- When player buys, spawn a new NPC and assign it to follow the player.****
dont worry, I'll code u an example with some comments to understand it perfectly !!
** # 1. NPC Follow Script (LocalScript or Script inside NPC model)**
local RunService = game:GetService("RunService")
local npc = script.Parent
local humanoid = npc:WaitForChild("Humanoid")
local targetPlayer = nil
local followDistance = 5
function follow(player)
targetPlayer = player
while targetPlayer and targetPlayer.Character and humanoid.Health > 0 do
local hrp = targetPlayer.Character:FindFirstChild("HumanoidRootPart")
if hrp then
local dist = (npc.HumanoidRootPart.Position - hrp.Position).Magnitude
if dist > followDistance then
humanoid:MoveTo(hrp.Position)
else
humanoid:MoveTo(npc.HumanoidRootPart.Position) -- stop moving
end
end
task.wait(0.5)
end
end
-- Start following the player when assigned
follow(game.Players:GetPlayers()[1]) -- For testing, follow first player
I'll give you an other one
2. Spawn & Assign NPCs to player (Server Script):
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Players = game:GetService("Players")
local npcTemplate = ReplicatedStorage:WaitForChild("FollowerNPC")
local playerFollowers = {}
Players.PlayerAdded:Connect(function(player)
playerFollowers[player.UserId] = {}
end)
function spawnFollower(player)
local npc = npcTemplate:Clone()
npc.Parent = workspace
npc:SetPrimaryPartCFrame(player.Character.HumanoidRootPart.CFrame * CFrame.new(3,0,3))
local followScript = npc:FindFirstChild("FollowScript")
if followScript then
followScript.Disabled = false
followScript:WaitForChild("BindableEvent"):Fire(player) -- Use BindableEvent or remote to tell which player to follow
end
table.insert(playerFollowers[player.UserId], npc)
end
-- Example buying function
function buyFollower(player)
spawnFollower(player)
-- deduct money here
end
3. Tell the NPC who to follow (update FollowScript)
local event = script:WaitForChild("BindableEvent") -- or RemoteEvent for remote communication
event.Event:Connect(function(player)
follow(player)
end)
Make your FollowScript listen for a BindableEvent or RemoteEvent to know the target player:
ty!!