How can i fix this getpartsinparts() issue?

  1. What do you want to achieve?
    R = Make the exit, enter area works like it should be.

  2. What is the issue?
    R = So, when you enter an area, a bool value will be set on true, telling you that someone is in there with a train, and if you are driving the train, you will get the welcome to station notification.
    Everything works fine until you leave the station and the value doesn’t go false, also i added a table that indicates the players that can’t be notified again until they leave the station, so the notification doesn’t repeat infinite times while being at the station, and it removes the players from the table once they are not in a station anymore, but like the value, it doesn’t to his job of removing the players. So when you go to the next station, his own value will go on, but you won’t get the welcome notification now, since you are in the table even if you left the past station, and his own value won’t go off once you are gone.

This occurs when there is more than 1 station in the station folder. If there is only 1 station, the system works fine.

  1. What solutions have you tried so far? Did you look for solutions on the Developer Hub?
    R = Trying to change tables position, making another functions.

Here is my code:

-- Services
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

-- Folders
local Modulos = ReplicatedStorage.Modulos
local Eventos = ReplicatedStorage.Eventos

-- Eventos
local Notificacion = Eventos.Notificacion

-- Parts
local Script = script.Parent
local Estaciones = Script.Estaciones
local DBOS = Estaciones.DBOS

local MensajeDeLlegada = "Mantente en la estacion hasta que el sonido DBO lo indique y puedas avanzar."

-- Table
local n = {}

-- Variables

local function RemoveVal(tbl, val) 
	for i,v in pairs(tbl) do
		if v == val then
			table.remove(tbl,i)
			break
		end
	end
end

function getPlayersInRegion()
	for i,e in Estaciones:GetChildren() do
		if e:IsA("Folder") and e.Name ~= "DBOS" then
			local Estacion = e
			local DetectArea = nil
			local parts = nil
			local DBOController = nil
			local DBOBVCDA = nil
			
			if Estacion:FindFirstChild("DBOCDAzteca") then
				
				local r = {}
				local t = {}
				
				DetectArea = Estacion:FindFirstChild("DBOCDAzteca") 
				parts = workspace:GetPartsInPart(DetectArea)
				DBOController = DBOS:FindFirstChild(Estacion.Name)
				DBOBVCDA = DBOController.CDAzteca
				
				for i, v in pairs(parts) do
					if v.Parent ~= nil then 
						if not table.find(t, v.Parent.Parent.Parent) then
							local Train = v.Parent.Parent.Parent				
							if Train ~= nil and Train.Name == "TRAIN" then
								table.insert(t, Train)	
	     					end				
						end	
					end
				end

				for i, player in t do
					if not table.find(r, player) then
						DBOBVCDA.Value = true
						if player:FindFirstChild("Dueño") then
							local Owner = player:FindFirstChild("Dueño")
							if Owner.Value ~= nil and not table.find(n, Owner.Value) then
								table.insert(n, Owner.Value)
								Notificacion:FireClient(Owner.Value, "Llegando a: "..Estacion.Name, MensajeDeLlegada, 7, "http://www.roblox.com/asset/?id=8076588158")
							end
							
						end
					end
				end
				
				for i, player in r do
					if not table.find(t, player) then
						RemoveVal(n, player)
						DBOBVCDA.Value = false
					end
				end
   

				r = t
				
			end
			
		end
	end
end


task.spawn(function(Check)
while task.wait() do
	local Players = getPlayersInRegion()
    end
end)

I hope you can help me with this little issue, i would thank you!

It seems you speak Spanish, so if you don’t mind, le pedí a ChatGPT que organizara mejor tu código para entenderlo mejor y esto fue lo que obtuve:

-- 🚀 Servicios de Roblox
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

-- 📁 Carpetas en ReplicatedStorage
local Modulos = ReplicatedStorage.Modulos
local Eventos = ReplicatedStorage.Eventos

-- 📢 Evento para enviar notificaciones a los jugadores
local Notificacion = Eventos.Notificacion

-- 📌 Partes del juego
local Script = script.Parent
local Estaciones = Script.Estaciones      -- Contiene todas las estaciones
local DBOS = Estaciones.DBOS              -- Controladores de estación

-- 📢 Mensaje mostrado al llegar a la estación
local MensajeDeLlegada = "Mantente en la estación hasta que el sonido DBO lo indique y puedas avanzar."

-- 📋 Tabla para almacenar jugadores que ya fueron notificados
local jugadoresNotificados = {}

-- 📌 Función para remover un valor de una tabla
local function RemoverJugadorDeLista(tabla, jugador)
    for i, v in tabla do
        if v == jugador then
            table.remove(tabla, i)
            break
        end
    end
end

-- 🚆 Función principal para detectar trenes en las estaciones
function getPlayersInRegion()
    for _, estacion in Estaciones:GetChildren() do
        if estacion:IsA("Folder") and estacion.Name ~= "DBOS" then
            local areaDeteccion = estacion:FindFirstChild("DBOCDAzteca")
            local partesEnArea = nil
            local controladorDBO = DBOS:FindFirstChild(estacion.Name)
            local estadoEstacion = nil

            if areaDeteccion then
                -- 🚨 Aquí está el problema
                local trenesAnteriores = {}   -- 🚫 Esta tabla se reinicia en cada iteración
                local trenesActuales = {}     -- 🚫 Esta también se reinicia

                partesEnArea = workspace:GetPartsInPart(areaDeteccion)
                estadoEstacion = controladorDBO and controladorDBO.CDAzteca

                for _, parte in partesEnArea do
                    if parte.Parent then
                        local posibleTren = parte.Parent.Parent.Parent
                        if posibleTren and posibleTren.Name == "TRAIN" and not table.find(trenesActuales, posibleTren) then
                            table.insert(trenesActuales, posibleTren)
                        end
                    end
                end

                for _, tren in trenesActuales do
                    if not table.find(trenesAnteriores, tren) then
                        estadoEstacion.Value = true

                        local dueño = tren:FindFirstChild("Dueño")
                        if dueño and dueño.Value and not table.find(jugadoresNotificados, dueño.Value) then
                            table.insert(jugadoresNotificados, dueño.Value)
                            Notificacion:FireClient(dueño.Value, "Llegando a: " .. estacion.Name, MensajeDeLlegada, 7, "http://www.roblox.com/asset/?id=8076588158")
                        end
                    end
                end

                for _, trenAnterior in trenesAnteriores do
                    if not table.find(trenesActuales, trenAnterior) then
                        local dueño = trenAnterior:FindFirstChild("Dueño")
                        if dueño and dueño.Value then
                            RemoverJugadorDeLista(jugadoresNotificados, dueño.Value)
                            estadoEstacion.Value = false
                        end
                    end
                end

                -- Esta asignación no tiene efecto si la tabla se reinicia en cada ciclo
                trenesAnteriores = trenesActuales
            end
        end
    end
end

-- 🕒 Bucle continuo para chequear las estaciones
task.spawn(function()
    while task.wait() do
        getPlayersInRegion()
    end
end)

El problema que veo (ChatGPT tambien lo vio)

Veo que estás reiniciando las tablas trenesAnteriores y trenesActuales en cada iteración dentro de la función. Por eso, los datos no se conservan entre ciclos, y la lógica de detectar si un tren salió de la estación falla.

¿Qué te recomiendo?

  1. Mueve la tabla trenesAnteriores fuera de la función para que persista entre iteraciones.
  2. Organiza el código con nombres descriptivos (esto ya te ayudará bastante).
  3. Usa IA’s (si aún no lo haces). Pueden ser de gran ayuda si las utilizas bien.

si es que puedes intenta consultar con alguna IA como ChatGPT si sigues teniendo problemas puedes preguntar aquí.

1 Like

El problema no se soluciono con este codigo, sin embargo lo refine con chat gpt como me recomendaste y el problema se soluciono al 100%. Gracias.

1 Like

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