简体   繁体   English

统一网络改变游戏对象精灵

[英]unity networking change gameobject sprite

I am creating a small online multiplayer game. 我正在创建一个小型的在线多人游戏。 and I managed some steps. 我设法做到了一些步骤。 I configured the player prefab and I managed to instantiate an object in the scene thanks to that: 我配置了播放器预制件,并由于以下原因设法实例化了场景中的对象:

[Command]
void Cmdbars()
{
    GameObject bar = Instantiate(barH, GameObject.Find("pos1").GetComponent<Transform>().transform.position, Quaternion.identity) as GameObject;

    NetworkServer.Spawn(bar);
}

Now I want that if we click on this object its sprite changes. 现在,我希望如果我们单击该对象,其精灵会发生变化。 for that I use this method: 为此,我使用这种方法:

[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";
        }
    }
}

The problem is that the sprite changes only locally and not in all players. 问题在于,精灵仅在本地更改,而不是在所有播放器中更改。

If you want to execute code on all clients you will use "Rpc" methods with ClientRpc attribute. 如果要在所有客户端上执行代码,则将使用具有ClientRpc属性的“ Rpc”方法。

For example in your case it must be like this: 例如,您的情况必须是这样的:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM