【UNET自学日志】Part7 独一无二的ID

时间:2022-09-04 03:53:42

在开始联机的时候,每一个Player 的名字都是Player(Clone),在这部分中我们需要把Player 的名字改成独一无二的标识符

新建一个脚本Player_ID

using UnityEngine;
using System.Collections;
using UnityEngine.Networking;

public class Player_ID : NetworkBehaviour {

[SyncVar]private string playerUniqueIdentity;
private NetworkInstanceId playerNetID;
private Transform myTransform;

public override void OnStartLocalPlayer()
{
GetNetIdentity();
SetIdentity();
}

void Awake()
{
myTransform = transform;
}

void Update ()
{
if (myTransform.name == "" || myTransform.name == "Player(Clone)")
{
SetIdentity();
}
}

[Client]
void GetNetIdentity()
{
playerNetID = GetComponent<NetworkIdentity>().netId;
CmdTellServerMyIdentity(MakeUniqueIdentity());
}

void SetIdentity()
{
if (!isLocalPlayer)
{
myTransform.name = playerUniqueIdentity;
}
else
{
myTransform.name = MakeUniqueIdentity();
}
}

string MakeUniqueIdentity()
{
string uniqueName = "Player " + playerNetID.ToString();
return uniqueName;
}

[Command]
void CmdTellServerMyIdentity(string name)
{
playerUniqueIdentity = name;
}

}

这段代码比较简单,也没什么好说的,大家看看就能理解~