This returns true if this object is the one that represents the player on the local machine.
In multiplayer games, there are multiple instances of the Player object. The client needs to know which one is for "themselves" so that only that player processes input and potentially has a camera attached. The IsLocalPlayer function will return true only for the player instance that belongs to the player on the local machine, so it can be used to filter out input for non-local players.
This example shows processing input for only the local player.
#pragma strict public class Player extends NetworkBehaviour { var moveX: int = 0; var moveY: int = 0; function Update() { if (!isLocalPlayer) { return ; } // input handling for local player only var oldMoveX: int = moveX; var oldMoveY: int = moveY; moveX = 0; moveY = 0; if (Input.GetKey(KeyCode.LeftArrow)) { moveX -= 1; } if (Input.GetKey(KeyCode.RightArrow)) { moveX += 1; } if (Input.GetKey(KeyCode.UpArrow)) { moveY += 1; } if (Input.GetKey(KeyCode.DownArrow)) { moveY -= 1; } if (moveX != oldMoveX || moveY != oldMoveY) { CmdMove(moveX, moveY); } } @Command function CmdMove(dx: int, dy: int) { // move here } }
using UnityEngine; using UnityEngine.Networking;
public class Player : NetworkBehaviour { int moveX = 0; int moveY = 0;
void Update() { if (!isLocalPlayer) { return; }
// input handling for local player only int oldMoveX = moveX; int oldMoveY = moveY;
moveX = 0; moveY = 0;
if (Input.GetKey(KeyCode.LeftArrow)) { moveX -= 1; } if (Input.GetKey(KeyCode.RightArrow)) { moveX += 1; } if (Input.GetKey(KeyCode.UpArrow)) { moveY += 1; } if (Input.GetKey(KeyCode.DownArrow)) { moveY -= 1; } if (moveX != oldMoveX || moveY != oldMoveY) { CmdMove(moveX, moveY); } }
[Command] void CmdMove(int dx, int dy) { // move here } }
Did you find this page useful? Please give it a rating: