Sdílet prostřednictvím


How To: Manage Players Joining and Leaving the Game

Manages the data associated with a player by subscribing to events that occur when players are joining or leaving a game.

A NetworkSession contains several properties that list the players who have joined a session. The collection of all gamers in a session is described by the property NetworkSession.AllGamers. This information is guaranteed to be the same on all game machines in a session. Within this list, the gamers might be local (playing on the same game machine through split-screen play) or remote (playing on a different game machine). The property NetworkSession.LocalGamers provides a list of all local players playing from a local game machine. The NetworkSession.RemoteGamers property provides a list of all players not playing on the local game machine.

To respond to players joining or leaving the game, you may subscribe to the NetworkSession.GamerJoined and NetworkSession.GamerLeft events with and create custom event handlers.

Subscribing to Gamer Events

To subscribe to gamer events

  1. After creating or joining a session, subscribe to the events that are associated with players joining or leaving the game.

    session.GamerJoined += new EventHandler<GamerJoinedEventArgs>(session_GamerJoined);
    session.GamerLeft += new EventHandler<GamerLeftEventArgs>(session_GamerLeft);
    
  2. Create the GamerJoined event handler.

    Note that the GamerJoinedEventArgs object contains a Gamer property. You can use it to read information about a specific player, or to associate information with a specific player. You can use the Gamer.Tag property to associate player data with the player.

    void session_GamerJoined(object sender, GamerJoinedEventArgs e)
    {
        // Associate a tank object with this gamer.
        e.Gamer.Tag = new Tank(Content, graphics.GraphicsDevice.PresentationParameters);
    
    }
    
  3. Create the GamerLeft event handler.

    void session_GamerLeft(object sender, GamerLeftEventArgs e)
    {
        Tank tank = e.Gamer.Tag as Tank;
    
        tank.LeaveGame();
    }
    

Note

If the host player leaves the session calling Game.Exit, this forces a host re-election. The host is automatically migrated to another player. If you are using a network topology other than peer-to-peer, such as a client-server or hybrid topology, and your host is also a server in the game, it will be necessary to migrate game state to the new game server when the host is migrated. Players in the game can use the HostChanged event to respond to host migration.

See Also

Concepts

Network Session Management

Tasks

How To: Create a Network Session
How To: Find and Join a Network Session