Edit: SOLVED. I just made the code less complex and moved things around
I’m making a system for entering and leaving a building and I have a problem where each time the code runs it runs an additional time time the next time it runs I managed to make a temporary fix by doing if self.fsm:is("Outside") then return end and if self.fsm:is("Inside") then return end but I’d like to try and avoid that haha.
This is my building class which uses a state machine to help do logic depending if the player is inside or outside. When the player interacts with the building it teleports them to a part and then uses my MessageSystem to run the fade screen code.
function Building.new(model)
local self = setmetatable(Interactable.new(),Building)
self.model = model
self.entranceModel = self.model.BPitEntrance
self.exitModel = self.model.BPitExit
self.interactBillboard = interactBillboard:Clone()
self.octreeNodes = {self.entranceModel.Part,self.exitModel.Part}
self.fsm = StateMachine.create({
initial = 'Outside',
events = {
{name = "Inside", from = "Outside", to = "Inside"},
{name = "Outside", from = "Inside", to = "Outside"},
},
})
return self
end
function Building:interact(characterModule)
print("Interacting With Building")
if self.fsm:is("Outside") then
self.fsm:Inside(characterModule)
MessageSystem:sendMessage(messageTypes.FadeScreen, {fadeTypes.FadeOut, callback = function()
if self.fsm:is("Outside") then return end
print("Teleport Inside")
characterModule:teleport(self.entranceModel.TeleportPart.CFrame)
MessageSystem:sendMessage(messageTypes.FadeScreen, {fadeTypes.FadeIn,nil,nil})
end})
elseif self.fsm:is("Inside") then
self.fsm:Outside(characterModule)
MessageSystem:sendMessage(messageTypes.FadeScreen, {fadeTypes.FadeOut, callback = function()
if self.fsm:is("Inside") then return end
print("Teleport Outside")
characterModule:teleport(self.exitModel.TeleportPart.CFrame)
MessageSystem:sendMessage(messageTypes.FadeScreen, {fadeTypes.FadeIn,nil,nil})
end})
end
end
This is the fade screen code
local function fade(fadeType,data)
local tween = nil
if fadeType == fadeTypes.FadeIn then
tween = fadeInTween
elseif fadeType == fadeTypes.FadeOut then
tween = fadeOutTween
end
tween:Play()
tween.Completed:Connect(function()
if data.callback then
data.callback()
end
end)
end
MessageSystem:registerListener(messageTypes.FadeScreen, function(data)
local fadeType = data[1]
fade(fadeType,data)
end)
And lastly this is the MessageSystem module that has the sendMessage and registerListener functions
-- Function to register a listener for a specific message
function MessageSystem:registerListener(message, listener)
if not listeners[message] then
listeners[message] = {}
end
table.insert(listeners[message], listener)
end
-- Function to send a message to all registered listeners
function MessageSystem:sendMessage(message, data)
if not listeners[message] then
return
end
for i, listener in ipairs(listeners[message]) do
listener(data)
end
end