Hello. I’m currently making a system where items drop from all players when they die.
I’m also adding AI so players can fight them. I ran into a problem though. How would I detect if a AI spawned. This only works for players and not the AI.
Players.PlayerAdded:connect(function(player)
player.CharacterAdded:connect(function(character)
local rootPart = character.HumanoidRootPart
local humanoid = character.Humanoid
local items = character.Items
local ammo = character.Ammo
humanoid.Died:connect(function()
DropEverything(character)
end)
end)
player.CharacterRemoving:connect(function(character)
local rootPart = character:FindFirstChild("HumanoidRootPart")
local humanoid = character:FindFirstChild("Humanoid")
local items = character:FindFirstChild("Items")
local ammo = character:FindFirstChild("Ammo")
if humanoid and humanoid.Health > 0 then
DropEverything(character)
end
end)
end)
Instead of looping through all the workspace, you could add every time you create a new AI to CollectionService Roblox offers using CollectionService:AddTag and listen for when a new AI is added CollectionService:GetInstanceAddedSignal
Here a simple example: Script 1:
local CollectionService = game:GetService("CollectionService")
--Code to add AI
local AIModel = Model
CollectionService:AddTag("Enemies", AIModel)
Script 2:
local CollectionService = game:GetService("CollectionService")
CollectionService:GetInstanceAddedSignal("Enemies"):Connect(function(model)
--Do whatever you want here
end)
Workspace.DescendantAdded:Connect(function(descendant)
if descendant.Name == "aiName" then
print("AI character added!")
local character = descendant
end
end)
When you run the function to spawn the AI, insert the properties you need from it into a global table, and when iterating over the table just Instance.Parent to the AI!