[英]unity networking change gameobject sprite
我正在創建一個小型的在線多人游戲。 我設法做到了一些步驟。 我配置了播放器預制件,並由於以下原因設法實例化了場景中的對象:
[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";
}
}
}
問題在於,精靈僅在本地更改,而不是在所有播放器中更改。
如果要在所有客戶端上執行代碼,則將使用具有ClientRpc
屬性的“ Rpc”方法。
例如,您的情況必須是這樣的:
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";
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.