我正在创建一个小型在线多人游戏。 我做了一些步骤。我配置了播放器预制件,我设法在场景中实例化一个对象,这要归功于:
[Command]
void Cmdbars()
{
GameObject bar = Instantiate(barH, GameObject.Find("pos1").GetComponent<Transform>().transform.position, Quaternion.identity) as GameObject;
NetworkServer.Spawn(bar);
}
现在我希望如果我们点击这个对象,它的精灵就会改变。 因为我使用这种方法:
[Command]
void Cmdclick()
{
if (Input.GetMouseButtonDown(0))
{
Vector2 origin = new Vector2(
Camera.main.ScreenToWorldPoint(Input.mousePosition).x,
Camera.main.ScreenToWorldPoint(Input.mousePosition).y);
RaycastHit2D hit = Physics2D.Raycast(origin, Vector2.zero, 0f);
if (hit && hit.transform.gameObject.tag.Equals("Untagged"))
{
hit.transform.gameObject.GetComponent<SpriteRenderer>().sprite = blueBarre.GetComponent<SpriteRenderer>().sprite;
hit.transform.gameObject.tag = "ok";
}
}
}
问题是精灵只在本地改变,而不是在所有玩家中改变。
答案 0 :(得分:1)
如果您想在所有客户端上执行代码,您将使用&#34; Rpc&#34;具有ClientRpc
属性的方法。
例如,在您的情况下,它必须是这样的:
private void OnClick()
{
Vector2 origin = new Vector2(
Camera.main.ScreenToWorldPoint(Input.mousePosition).x,
Camera.main.ScreenToWorldPoint(Input.mousePosition).y);
CmdOnClick(origin.x, origin.y);
}
//this code will be executed on host only, but can be called from any client
[Command(channel = 0)]
private void CmdClickHandling(float x, float y)
{
RpcClick(x, y);
}
//this code will be executed on all clients
[ClientRpc(channel = 0)]
private void RpcClickHandling(float x, float y)
{
//quit if network behaviour not local for preventing executing code for all network behaviours
if (!isLocalPlayer)
{
return;
}
Vector2 osrigin = new Vector2(x, y);
RaycastHit2D hit = Physics2D.Raycast(origin, Vector2.zero, 0f);
if (hit && hit.transform.gameObject.tag.Equals("Untagged"))
{
hit.transform.gameObject.GetComponent<SpriteRenderer>().sprite = blueBarre.GetComponent<SpriteRenderer>().sprite;
hit.transform.gameObject.tag = "ok";
}
}