Disconnect a player from a network

I am very new to networking. I am working on a simple script that will stop players from joining it if the game has been started. Networking to me seems (at times) unreasonably difficult.

Maybe I’m just not good at google searching.

Before i post my code, i will tell you what i searched for, if any of these exist, they would be extremely helpful. I couldn’t find a one.

A method, to stop any new clients from joining the network

A way to diconnect a player by ip address (this one would be especially helpful)

A way to make a client disconnect itself.

As far as i know Network.CloseConnection seems to be the only way to do this. Although, i don’t really know what CloseConnections even does. I found the example script for it in the documentation really long and hard to understand. from my knowledge it seems to disconnect a target connection (whatever the heck that is). I assume that this is a player instance in the Network.connections Array. but then again i have no clue.

here’s a sample of my code (not all of it). It doesn’t work am i doing something wrong?

function allowentry (){

         if(startgame == true){
	          Network.CloseConnection(Network.connections[Network.connections.length], true); // this was supposed to get rid of the last player that connected


//bunch of GUI buttons unnecessary to the explanation to my code stuff here 

 Network.Connect(words, connectionPort); // it connects fine
networkView.RPC("allowentry", RPCMode.Server);

//yes the network view is attached to my object

This results in nothing happening. all of my code runs ( i found this out through console statements) but I get no error, no nothing. just a client that was not kicked out of the server.

I even tried changing line 5 to

	Network.CloseConnection(Network.connections[1], true);

because i was currently testing this with only one client and one server, but i got this error message

IndexOutOfRangeException: Array index is out of range.
Connect.allowentry () (at Assets/Connect.js:19)

so sorry this was so long, and that i am such an idiot. thanks a whopping bajillion for reading this.

+1 for being humble and polite :wink: And you’re no idiot - networking is the single hardest component to nail that I’ve ever encountered. The only obvious mistake I can see in the above code is that, since array indexes are zero-based, to disconnect the last player,

Network.CloseConnection(Network.connections[Network.connections.length], true);

should be:

Network.CloseConnection(Network.connections[Network.connections.length - 1], true);

If you manage to get Network.CloseConnection() working in the general sense, you should be able to target a particular player to disconnect by testing the ipAddress property of the NetworkPlayer: Unity - Scripting API: NetworkPlayer.ipAddress - I might be able to knock up a quick example this evening.