Hi. I have a problem with my spawn module. The error said: attempt to index nil with newEnemy. I’ve tried everything but i don’t know what’s causing it.
spawn module code:
local serverStorage = game:GetService("ServerStorage");
local enemies = serverStorage:FindFirstChild("Enemies");
local map = game.Workspace:WaitForChild("Map");
local waypoints = map:FindFirstChild("Waypoints");
local enemy = {}
enemy.__index = enemy
-- spawn
function enemy.spawn(enemyName)
local self = setmetatable({}, enemy)
-- enemy exist
self.enemyExist = enemies:FindFirstChild(enemyName);
if self.enemyExist then
-- new enemy
self.newEnemy = self.enemyExist:Clone();
self.newEnemy.HumanoidRootPart.CFrame = map:FindFirstChild("EnemyBase").CFrame;
self.newEnemy.Parent = game.Workspace:FindFirstChild("Enemies");
enemy.move();
end
return self
end
-- move
function enemy:move()
-- waypoints
for waypoint = 1, #waypoints:GetChildren() do
self.newEnemy.Humanoid:MoveTo(waypoints[waypoint].Position);
self.newEnemy.Humanoid.MoveToFinished:Wait();
end
end
return enemy
yea so in this case its just not properly indexing it or it doesnt exist.
You use this to define enemies
local enemies = serverStorage:FindFirstChild("Enemies");
Instead try this
local enemies = serverStorage:WaitForChild("Enemies");
We know that enemies does infact exist, so theres no point in existence checking it. It also doesn’t factor that this is probably running when the game starts up, so it actually won’t find it at all.