OOP Enemy Classes

I want this system to be easily extendable meaning I can have different types of enemies and behaviors

example (an enemy can have a sword class and another enemy could have a fireball class)

so far my idea is to use OOP since I can reuse code that all enemies will share and also add unique code

Base Class

local EnemyClass = {}
EnemyClass.__index = EnemyClass

function EnemyClass.new()
	local self = setmetatable({}, EnemyClass)
	self.enabled = false
	return self
end


function EnemyClass:enable()
	if not self.enabled then
		self.enabled = true
		self:start()
	end
end

function EnemyClass:spawnCharacter() -- added for insight
-- spawn enemy physical character
end
return EnemyClass

Sword Class

local EnemyClass = require(script.Parent.EnemyClass)
local EnemySwordClass = setmetatable({}, {__index = EnemyClass})
EnemySwordClass.__index = EnemySwordClass

function EnemySwordClass.new()
	local self = setmetatable(EnemyClass.new(), EnemySwordClass)
	self.sword = "some sword here"
	return self
end

function EnemySwordClass:start()
	print("started")	
end

function EnemySwordClass:stop()
	print("stopped")	
end

function EnemySwordClass:equipSword() -- added for insight
-- attach sword to character here
end
return EnemySwordClass
local enemy = EnemySwordClass.new()
enemy:enable()

Game Starts >> Create all enemy objects >> Enable when player is in zone >> Do enemy stuff (spawn it’s physical self, combat, die, respawn, etc) >> Disable when player leaves zone

posting this here instead of code review because this is less of how to improve my “already working code” and more about if this the correct concept I should be using (I tend to do more than work necessary)

majority of my research was in different programming languages, as it’s really not easy finding practical lua resources on stuff like this

my only other idea is to copy scripts into every enemy, but that isn’t exactly efficient as I would have to constantly clone scripts every time an enemy dies and I’d have an extreme amount of scripts because of that

Edit: added two more methods to give insight

2 Likes

this is actually spot on, found it by accident couldn’t find it earlier because the title of the post didn’t match what I was searching

2 Likes