UNET Multi-Player game, having both players interact with gameObject, changes synchronized on host and client

此生再无相见时 提交于 2019-12-04 17:40:09

So I finally was able to get this to work, thanks to this StackOverflow post.

Here's my script, I attached it to the Player Object, not the non-Game Object that I wanted to be synchronized over the network.

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

public class OnTouchEvent : NetworkBehaviour
{
    //this will get called when you click on the gameObject
    [SyncVar]
    public Color cubeColor;
    [SyncVar]
    private GameObject objectID;
    private NetworkIdentity objNetId;


    void Update()
    {
        if (isLocalPlayer)
        {
            CheckIfClicked();
        }
    }

    void CheckIfClicked()
    {
        if (isLocalPlayer && Input.GetMouseButtonDown(0))
        {
            objectID = GameObject.FindGameObjectsWithTag("Tower")[0];                         //get the tower                                   
            cubeColor = new Color(Random.value, Random.value, Random.value, Random.value);    // I select the color here before doing anything else
            CmdChangeColor(objectID, cubeColor);
        }
    }



    [Command]
    void CmdChangeColor(GameObject go, Color c)
    {
        objNetId = go.GetComponent<NetworkIdentity>();        // get the object's network ID
        objNetId.AssignClientAuthority(connectionToClient);    // assign authority to the player who is changing the color
        RpcUpdateCube(go, c);
        // use a Client RPC function to "paint" the object on all clients
        objNetId.RemoveClientAuthority(connectionToClient);    // remove the authority from the player who changed the color
    }

    [ClientRpc]
    void RpcUpdateCube(GameObject go, Color c)
    {
        go.GetComponent<Renderer>().material.color = c;
    }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!