Amine Ouam
Amine Ouam

Reputation: 3

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.

Upvotes: 0

Views: 1153

Answers (1)

Sergiy Klimkov
Sergiy Klimkov

Reputation: 540

If you want to execute code on all clients you will use "Rpc" methods with ClientRpc attribute.

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

Upvotes: 1

Related Questions