I'm working on first person game where player can build complex objects. Structure example:
Train
- Wagon
- Table
- Chair
- Chest (stores items)
- Workshop (manufactures items, has build queue)
Player is able to create trains, add wagons, place objects into wagons, modify placed objects. Whole train can move, objects are in transform hierarchy.
Player can interact with placed objects (e.g. put items into chest, modify workshop build queue), so I need a way to identify them across network. This indicates that all objects should have NetworkIdentity
. Some objects have also their state which needs to be synced (stored items, build queue).
What's suggested synchronization approach? Which objects should have NetworkIdentity
?
Adding NetworkIdentity
to all of them prevents me from creating Train prefabs in Editor (prefabs can have NetworkIdentity
only on root), but I could probably live with that. I have to also "manually" set parent when wagon or object is spawned on client.
Another solution might be to add NetworkIdentity
only to Train and then identify objects by some ID within the train. I cannot imagine how to use SyncVar
with this approach, since everything would have to be on the Train.
Solution
NetworkIdentity
to all objects in hierarchyPrefab 'xxx' has several NetworkIdentity components attached to itself or its children, this is not supported.
We need to ensure that client receives child object only when it has parent. We also need to ensure that client receives child object soon when it receives parent.
This is achieved by
OnRebuildObservers
andOnCheckObserver
. These methods check whether client has parent object, when it does it adds player connection to list of observers, which causes player to receive the object.We also need to call
NetworkIdentity.RebuildObservers
when parent object is spawned. This is achieved by custom connection class, which notifiesMultiplayerGame
when object is spawned on client (connection sends Spawn message).Full scripts are below.
NetworkChild
Base class for network component on objects which are children, e.g. wagon, object in wagon.
NetworkNotifyConnection
Custom connection class which notifies
MultiplayerGame
when Spawn and Destroy message is sent to client.MultiplayerGame
Component on
NetworkManager
, which sets custom network connection class when server is started.