Identifying the Local Player

Checked with version: 5.3

-

Difficulty: Intermediate

The player GameObjects are currently identical. The players cannot identify which GameObject belongs to them in the game. To identify which GameObject belongs to the local player, we will color the local player GameObject blue.

  • Open the PlayerController script for editing
  • Add an implementation of the OnStartLocalPlayer function to change the player object’s color.
public override void OnStartLocalPlayer()
{
    GetComponent().material.color = Color.blue;
}

The final script will look like this:

PlayerController

Code snippet

using UnityEngine;
using UnityEngine.Networking;

public class PlayerController : NetworkBehaviour
{
    void Update()
    {
        if (!isLocalPlayer)
        {
            return;
        }

        var x = Input.GetAxis("Horizontal") * Time.deltaTime * 150.0f;
        var z = Input.GetAxis("Vertical") * Time.deltaTime * 3.0f;

        transform.Rotate(0, x, 0);
        transform.Translate(0, 0, z);
    }

    public override void OnStartLocalPlayer()
    {
        GetComponent<MeshRenderer>().material.color = Color.blue;
    }
}

This function is only called by the LocalPlayer on their Client. This will make each player see their local player GameObject as blue. The OnStartLocalPlayer function is a good place to do initialization that is only for the local player, such as configuring cameras and input.

There are many other useful virtual functions on the NetworkBehaviour base class. For more information, please see the pages on Spawning or NetworkBehaviour.

  • Save the script.
  • Return to Unity.
  • Build and Run this scene as a standalone application.
  • Click the Host button from the in-game UI to start this game as a Host.
  • Move the player GameObject.
  • Return to Unity.
  • Enter Play Mode.
  • Click the LAN Client button from the in-game UI to connect to the Host as a Client.

The player GameObject controlled by the local player should now be blue, while the other player GameObject should remain white.

description

  • Close the standalone player.
  • Return to Unity.
  • Exit Play Mode.

Related documentation