Adding a property to a base class, but keeping it separate across subclass instances

This has been a big issue for me in regards to events, but seems like it might be making further problems. Say I have three classes A, B and C such that:

A is the base class and has an event called Updated
B is a subclass of A and provides a function to fire off the Updated event
C is an external class which links to a specific B to listen for the Updated event

The problem is that if I have multiple Bs and Cs, where every C connects to one specific B, the Cs will fire off for any event on A. So, say I have two Bs and two Cs, B1, C1, B2, and C2; if the event fires from B1, then both C1 and C2 will respond to it, but I only want C1 to respond.

I’m able to fix it by moving the event into B1, but that’s a bit more difficult when I have more properties/events added into A / more subclasses branching off from it. It might just be because I’m used to other languages, but is there something I’m doing wrong here or will I just have to live with putting the properties into the children classes?

2 Likes

To add some code as an example:

local A = { }
A.__index = A

function A:Init()
	local self = setmetatable({
		Updated = Instance.new("BindableEvent")
	}, self)
	self.__index = self
	return self
end
function A:Update()
	-- Logic
	self.Updated:Fire()
end


local B = A:Init()
B.__index = B

function B.new()
	return setmetatable({ }, B)
end
function B:DoSomething()
	self:Update()
end

return B


local C = { }
C.__index = C

function C.new()
	local self = setmetatable({
		_b = B.new()
	}, C)
	
	self._b.Updated:Connect(function()
		print("Update!")
	end)
end

Now if I create multiple Cs and one of those Bs fires Updated, all the Cs will react. I’m trying to get it to where every C reacts to its own B’s event but none of the others. Is there any easy way of doing that?

1 Like

In your code block you create one subclass of B using A:Init(). Instead, try calling A:Init() every time B.new() is called.

local B = A
B.__index = B

function B.new()
	return setmetatable(A:Init(), B)
end
function B:DoSomething()
	self:Update()
end

return B
2 Likes

You are an absolute lifesaver, thank you very much!