Skip to main content

Identifying the players on joining the game

This assumes that you have created a Player Spawn Manager script in the previous lesson.

Identifying the Player

Now we want to be able to identify the player easily. This guide will just show how to find the playerIndex which is a unique number for the player. It starts at 0 for the first player and increments as players join.

Modify the method constructor to take a PlayerInput playerInput argument.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;

public class PlayerSpawnManager : MonoBehaviour
{
public GameObject[] spawnLocations;

void OnPlayerJoined(PlayerInput playerInput) {
Debug.Log("PlayerInput Joined");
}
}

Now modify the Debug.Log method on line 11 so that it prints out a message "PlayerInput ID: " and then the playerIndex.

We can access the index (id) of the player through the PlayerInput object that is created when a player joins.

To do this we use dot notation to access the playerIndex property of playerInput with the code playerInput.playerIndex

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;

public class PlayerSpawnManager : MonoBehaviour
{
void OnPlayerJoined(PlayerInput playerInput) {

Debug.Log("PlayerInput ID: " + playerInput.playerIndex);

}
}

Test and run the program.

You can now see that three players have joined each with the index 0, 1, and 2 respectively in the order that they joined the game.