Spawn module attempt to index nil

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. :slightly_frowning_face:

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

Try printing out what self.enemyExist is. It may not be registering it as the right data type, so when you attempt to clone it, it doesn’t work.

The print said that the self.newEnemy is nil.

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.

It didn’t work i still got the same error.

Try checking the script which uses enemy.spawn(enemyName) it looks like you aren’t properly passing an enemy name through the function.

I don’t think is see a problem with the enemy script.

enemy script:

local serverStorage = game:GetService("ServerStorage");
local enemy = require(serverStorage:WaitForChild("EnemyModule"));

enemy.spawn("Weak Zombie");

i’ve found the problem but there is a second problem.
First problem was that.

I used this

enemy.move();

instead of this

enemy:move();

Now the second problem said: attempt to index nil with ‘Humanoid’

You have to store the enemy, and then use :move() on that specific variable.

local zombie = enemy.spawn("Weak Zombie")
zombie:move()

it didn’t work i just got the same error again.

Nevermind I’ve fixed the problem thanks everyone. :grinning:

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.