I am building a Runnig Race Multiplayer Game in Unity3D using UNET. I have 2 Player running straight in a game Subway Surfer. I want to update position of the player while running who is first and who is second and vice versa, the code is working for Host Player but not updating other player postion. Please help me what i am doing wrong.
Here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class PlayerPosition : NetworkBehaviour {
GameObject[] Players;
Vector3 playerPos;
void Start () {
InvokeRepeating("UpdatePosition", 0.5f, 0.5f);
}
void UpdatePosition () {
if (!isLocalPlayer)
return;
ClientPositionCalls();
}
[Client]
void ClientPositionCalls()
{
CmdServerPosition();
}
[Command]
public void CmdServerPosition()
{
Position();
}
[Server]
public void Position()
{
playerPos = transform.position;
RpcPosition(playerPos);
}
[ClientRpc]
void RpcPosition(Vector3 pos)
{
if (isLocalPlayer)
{
playerPos = pos;
Players = GameObject.FindGameObjectsWithTag("Player");
foreach (GameObject p in Players)
{
if (p.transform.position.z < pos.z)
PlayerCanvas.canvas.WritePositionText("1");
else
PlayerCanvas.canvas.WritePositionText("2");
}
}
}
}
So here is the Answer fixed by my self. What I did is I added 2 Slider for Player Position Indicator to show who is first and who is second, and I set the minimum value of Slider to Start Position of Player and Max Value to Finish Position of the Player and then I compared the value of slider.
here is the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
public class PlayerPosition : NetworkBehaviour {
GameObject[] Players;
Vector3 playerPos;
// Update is called once per frame
void Update() {
if (!isLocalPlayer)
return;
ClientPositionCalls();
if (PlayerCanvas.canvas.hostDotObj.GetComponent<Slider>().value > PlayerCanvas.canvas.clientDotObj.GetComponent<Slider>().value)
{
PlayerCanvas.canvas.WritePositionText("1");
} else
{
PlayerCanvas.canvas.WritePositionText("2");
}
}
[Client]
void ClientPositionCalls()
{
CmdServerPosition();
}
[Command]
public void CmdServerPosition()
{
playerPos = transform.position;
RpcPosition(playerPos);
}
[ClientRpc]
void RpcPosition(Vector3 pos)
{
if (isLocalPlayer)
{
PlayerCanvas.canvas.hostDotObj.GetComponent<Slider>().value = transform.position.z;
playerPos = pos;
} else
{
PlayerCanvas.canvas.clientDotObj.GetComponent<Slider>().value = pos.z;
}
}
}