Player.Chatted breaks after a while?

I have a simple radio system setup; a player stands near a part, when they chat it broadcasts their chat to other radio parts. This works fine for 20~ minutes, until it breaks suddenly.


This is the error I get,
here’s line 28

function listenForChat(char, relay)
	local db = false
	
	local player = Players:GetPlayerFromCharacter(char)
  >line 28   	local connection
    	connection = 	player.Chatted:Connect(function(msg)
		
		if not db then db = true
			print(msg)
		connectRelays(player, msg)
		
		wait(.6)
		pInRange = false
		db = false
		connection:Disconnect()
		
		end
		end
	)

end

I honestly can’t figure out why this happens. I don’t know if player is nil or chatted is nil or what is going on

1 Like

Index means ‘to read from’
The error means that you are trying to get an event, property, or child of something that the script can’t find. It just doesn’t EXIST in the reference you provided.

In short, this means that “player” is nil.

(At first I couldn’t figure out why this was happening either but then I saw that you disconnect it as well, meaning that it would have to be reconnected later on)

The problem is that you don’t account for when the player leaves the game. My advice would be to check if the player exists BEFORE connecting a function to the .Chatted event.
Add between line 27 and 28,
if not player==nil then.

Hope this helped!

1 Like

In my opinion you are calling the player incorrectly because you are defining it’s character instead of calling it from ‘Players’ service. This might be a fix:

local player = game:GetService("Players"):FindFirstChild(Players:GetPlayerFromCharacter(char).Name)
1 Like

GetPlayerFromCharacter returns the player instance, so there is no need to do all that.

Also, he said that it works fine for about 20 mins, which must be when the player leaves the game.

Another fact is that the :GetPlayerFromCharacter API says that it returns nil if a player cannot be found, and the error says that nil is being indexed with .Chatted.

2 Likes