简体   繁体   中英

Unity3d Unet sync gameObject List

I am trying to sync a list of gameObjects across the network using unity3d's networking engine unet. The list is initialized on the server and objects are added to it. I want this list to be synced across all players such that if a single player adds to it, its updated across the network , and if a player removes an item to it its updated across the network. I understand I am supposed to use clientRPC or Commands, however i am unable to figure out how to use them specifically. There are no good examples that i can find syncing a list like this. If anyone could point me in the right direction it would be great.

A client that wishes to manipulate the list will have to execute a command on the server which will in turn tell all clients how to manipulate the list. Assume you have the following NetworkBehaviour on all your player objects (all of which have Local Player Authority on their respective client).

public void ListManipulator : NetworkBehaviour
{
    public void AddToList(GameObject obj)
    {
        if (!isLocalPlayer)
            throw new InvalidOperationException("This can only be called for the local player!");
        if (obj.GetComponent<NetworkIdentity>() == null)
            throw new InvalidOperationException("Network only knows about GameObjects that have a NetworkIdentity!");

        CmdAddToList(obj);
    }

    [Command]
    void CmdAddToList(GameObject obj)
    {
        // this code is only executed on the server
        RpcAddToList(obj); // invoke Rpc on all clients
    }

    [ClientRpc]
    void RpcAddToList(GameObject obj)
    {
        // this code is executed on all clients
        localCopyOfList.Add(obj);
    }
}

Note that every client will have their own local copy of the list: localCopyOfList .

Also, if you can not guarantee that the target objects have NetworkIdentity components, you can instead give them names or ids or similar and use these to communicate which items to add or remove.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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