Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Authority | Authority transfer | Network Commands
In a networked game, an object's logic is always run by one node on the network, whether it's a Client or a Server (which we call a Simulator in coherence). We say that the node "has authority" on the network entity.
There are cases where it makes sense to transfer authority, like it happens in this project with objects that can be picked up. When the player grabs an object, the Client performing it requests authority over the network entity. Once it gets authority it starts running its scripts and has full control over it. This is a very good way to go when only one player can interact with a certain object at a given time.
For more info, check the lesson about transferring authority in the First Steps project.
However, there are cases when we don't want to change who has authority on an entity. In the case of an object that many players can interact with at the same time, it wouldn't make sense to continuously move authority between nodes.
The interaction with such remote entities then needs to happen entirely through Network Commands.
In this project, it is the case of the chairs placed in the scene. The first Client or Simulator to connect will take authority over them, and it will keep it until they disconnect.
When a player wants to sit down on a chair, they inform the Authority that they are doing so. The client holding authority will then set the chair as busy, which prevents other players from sitting on it next time they try.
However, for the sake of simplicity and to illustrate the point, we intentionally left this interaction a bit flaky. Can you guess why? What could go wrong with this setup?
The action originates in SitAction.cs
:
SitAction
checks if the isBusy
property of the chair is set to true
(by the authority, of course). If so, it means someone else is already sat on the chair. If false
, we can sit. So it invokes Chair.Occupy()
.
And further down, the essence of the interaction:
So both when occupying a chair (Occupy()
) or standing up (Free()
), the player executing the action invokes the ChangeState
method, either directly or as a Network Command - depending if they are the one with authority.
So one way or the other, ChangeState
gets executed on the authority, who sets the isBusy
property to its new value. On the next coherence update, the property will be sent to the other Clients.
The answer: Clients are using the isBusy
property as a check for whether they can sit or not. It is possible that two players will approach a chair at the same time, check if isBusy
is false (and yes, it will be false), at which point they will inform the authority that want to sit down on it.
The authority performs no additional checks, so you will see both players successfully sitting on the chair, overlapping on each other.
Thankfully we also coded the rest of the interaction so that this doesn't break the game. So while this incidence and the consequences for this interaction are low-risk, if you're looking to create a more robust system it could make sense to implement a check on the authority, and have the Client wait for an answer before they sit down.
We do this in other parts of the demo, like when chopping a tree or when picking up an object. Check the following section on chopping trees to explore this similar but more complex use case.
| |
Network entities need to be created and removed all the time. This can be due to entities getting in and out of a LiveQuery, or simply because gameplay requires so. If that is the case, we can leverage coherence's object pooling system in order to avoid costly calls to Instantiate
and Destroy
, which are famously expensive operations in Unity.
In this project we use pooling for one very clear use case: the tree logs that get spawned when chopping down a tree.
This was a natural choice as players will be chopping trees all the time, but we can also assume that they will burn the logs on the fire almost as often. So by pre-allocating a pool of around 10 logs, we should be covered in most cases.
To set up the log to behave like this, all we did was to set that option on the log's own CoherenceSync
inspector.
A pool configured like this means that coherence will pre-spawn 10 instances of the Prefab at the beginning of the game.
However if we were to need more, we could request more instances and they would be created and added to the pool. The game can even go above 20. If that were to happen, any instance released beyond 20 wouldn't just be returned to the pool, but would be destroyed.
In other words, 10 and 20 represent the lower and upper limit for the amount of memory we are reserving for the logs alone in our game. We are considering anything above 20 as a temporary exception.
When we press Play, coherence instantiates these 10 logs, deactivate them, and put the pool in the DontDestroyOnLoad scene:
Because they are inactive, their CoherenceSync
components are not syncing any value.
To spawn a new log we only need to call one line of code. However, we don't provide a reference to a regular Prefab like we would with Instantiate
. We instead leverage the CoherenceSyncConfig
object that represents the log.
This CoherenceSyncConfig
contains all the info that coherence needs to handle this particular Prefab over the network. If we inspect it, we will notice that it contains in fact how the object is loaded (Load via) and how it's instantiated (Instantiate via).
You can notice how this is the same info we saw while configuring the CoherenceSync
before.
Now that we have a reference to it, we can spawn the log with one line of code. In the ChoppableTree
script, we do something like:
This line looks remarkably similar to Unity's own Instantiate
in its syntax. The difference is that it gives us back a reference to the CoherenceSync
attached to the log instance that will be enabled. From this, we can do all sorts of setup operations by just fetching other components with GetComponent
, to prepare the instance.
When we are done with it (in this case, when it's thrown into the campfire), we can dispose of it:
(this line is in the Burnable.cs
class, inside the GetBurned()
method)
The instance is then automatically returned into the pool, and disabled.
When taking an instance out of the pool or when returning it, coherence doesn't automatically do any particular clean up to its state.
As such, when we reuse a pool instance, it is good practice to think of what values should be reset that might have been messed up by previous usage. We should think about what happens during gameplay, and use OnEnable
/ OnDisable
as needed to ensure that disabled instances are put in a state that makes them ready to be used again.
For this project, since an object can be burned while being carried, we do some cleaning in the OnDisable
of the Grabbable.cs
class to prepare the wood logs for another round, like so:
| |
It's often the case that in addition to objects being fully owned by players, like their characters, there is often the need to have objects that exist only in one copy in the world and that need to store a complex state that needs to be reflected in the same way on each Client. And the state might not be a simple int
or bool
that can be just automatically synced over the network whenever it changes, but something more complex that requires to be elaborated.
This is often the case for more invisible objects like a leaderboard, a spawn point, a score counter or a match timer; but can also be the case for objects that have graphics.
An example of such an object, that also happens to be very central to this demo, is the campfire. As the players pick up objects and throw them on the fire, the campfire needs to perform a calculation based on a timer and the type of the object burned to decide which fire effect to play.
Timing is key here! If two players throw in two objects, one right after the other, they activate a special effect that makes the campfire burn bigger and brighter. But the two objects need to get on the fire within 2.5 seconds from each other (it's the teamEffortLength
variable in the Campfire.cs
script).
Because this calculation depends on the timer value that is managed by the Authority, we can't just independently calculate a result on each Client, as they would almost certainly end up with different results. We need to inform the Authority that the action is taking place, let it figure out the final state, and only then propagate the resulting state and actions to all Clients.
(1) Action happens on a Client -> (2) Authority campfire is notified, processes result -> (3) Authority campfire sends result to all others -> (4) Non-authority campfire objects execute local effects
We do have an extra challenge here though. Ultimately we want the Authority to inform everyone to play specific visual and sound effects depending on the object burned. But we can't send Network Commands with a reference to audio assets or particle systems. So we need to change this information to something we can send, and then on the receiving end, "unpack it" and transform it into the info we actually need (i.e., which sound).
If you look into the Campfire.cs
script, you will find this sequence of actions as exemplified by the flow below:
(1) The player throws an object on the fire. BurnObjectLocal()
is invoked by the Burnable
that collided with the Campfire
. The script checks if Authority is already on this Client:
The method invoked in both cases is BurnObject()
, but it's invoked differently depending on whether it is local (direct invocation) or remote (using SendCommand
via the CoherenceSync
).
We use the ID of the CoherenceSyncConfig
of the object that burned as a parameter. The ID is a string, so it's something we can send over the network.
(2) The logic for which fire effect to play is then calculated in BurnObject()
.
The campfire uses the CoherenceSyncConfig
ID as a key to look into the CoherenceSyncConfigRegistry
, and find the right object archetype to play the right effect.
(3) ChangeFireState()
is invoked locally on the Authority. Here the Authority updates its own property activeFireEffect
which, being a synced property, gets sent to the other Clients.
But updating that int wouldn't be enough to tell which sound to play, so we send a command to invoke the FireStateChanged()
method, passing the CoherenceSyncConfig
ID which the non-authoritative campfire instances can use to trace down the object that burned in the CoherenceSyncConfigRegistry
.
(4) The non-authoritative clients execute FireStateChanged()
, which turn on/off the appropriate fire particles, and play a specific sound.
If the Client (or a Simulator) detaining the authority on the campfire disconnects, we need to make sure that whoever gets assigned authority next can pick up the job exactly where it was left off, and continue simulating the campfire logic without interruption.
That's why in the Campfire.cs
class we make sure to sync three values:
activeFireEffect
is an index (expressed as an integer) of which fire effect should be playing right now.
fireTimer
and bigFireTimer
are two countdowns that indicate how much time the fire will still burn normally or, when in "big fire mode", brighter.
However, there's an opportunity to be smart here. fireTimer
and bigFireTimer
are variables that are updated every Update on the Authority, but they are only useful in case the Authority gets transferred. So what we can do using the Optimization panel is to reduce the frequency they are sent to other Clients to a much more manageable value of once every second.
This might not be very precise and would have been unacceptable in the case of a visible timer, but here it doesn't matter. To the players this is going to be invisible, but we avoid a lot of network traffic.
As mentioned before, this mini state-machine behavior can run perfectly on one of the connected Clients. There is one catch though: this way, if no one is connected, the fire will stop updating because no one is simulating it, and thus it will never burn out.
Try this: connect, throw an object on the fire, disconnect, and reconnect after some time. The value of fireTimer
will still be the same and so the fire will still be burning no matter how much time has passed.
Using an Authority transfer, it is trivial to let this behaviour run on a Simulator if there is one connected. Look into the Campfire
class, within OnLiveQuerySynced
:
With this simple code, whenever a Simulator connects and sees the persistent campfire network entity, it will take Authority over it. If it were ever to go offline and a client is connected, that Client would take back Authority. If the Simulator comes back online, it would steal it again. And so on.
While this is not a cheat-proof solution, it can be useful for various scenarios.
Having a behavior set up this way allows the Prefab and its logic to be used in an offline mode without modification (because the offline player would act as the owner Client). This can be useful to create a free demo version; a tutorial mode; or even to showcase the game in conditions of limited connectivity.
You could launch the game with no Simulators to run a game preview while keeping costs down, like during an Early Access or a Steam festival. Later on when it goes live, the game could be switched to use a Simulator, and no change to the code would be required.
| |
We saw in the previous section about how sometimes it makes sense not to move authority around between Clients. At this point, Network Commands are the way to interact with a remote object.
Now let's take a look at another case of remote object, where the interactions with it need to be validated by the one holding authority, to avoid nasty cases of concurrency.
In this project, it is the case of the trees that are placed in the scene. The first Client or Simulator to connect will take authority over them, and it will keep it until they disconnect.
When a player wants to chop a tree, they request the Authority to subtract 1 unit of energy. When the energy runs out, it's the Authority that spawns a new Log instance.
This centralization, as opposed to passing authority around, allows multiple players to chop the same tree at the same time and prevents many race conditions, because the important action (destroying the tree and spawning the log) is all resolved on the Client with Authority.
Conceptually, we can imagine the event flow to go like this:
(1) Chop action happens on a Client -> (2) Authority is notified, elaborates new state -> (3) Authority sends result to all others -> (4) All other Clients play out animation and effects
You can find this flow in practice in the ChoppableTree.cs
script. In this script, only one variable is synchronized, the energy of the tree:
The flow goes like this:
(1) A player presses the button to chop down the tree.
It locally invokes the method TryChop()
, which checks if the tree hasn't been already chopped down, subtracts energy locally, and also invokes the Chop()
method, locally or remotely depending if authority on this tree is here or not.
(2) On the Authority, the Chop()
method is called, and checks if the tree needs to be effectively cut down based on its energy:
(3) If so, CutDown()
is invoked locally, spawning the log and informing all other clients to play the animation of the tree disappearing:
(4) Finally, other Clients play animation, particles and sound locally in ChangeState()
. They will also see the log spawn thanks to the automatic network-instantiation.
Why do we subtract energy from a synced variable in TryChop()
when we are not the Authority?
Ultimately, the final word on whether the tree has been chopped down completely is always on the Authority's side, of course. But by subtracting energy locally and immediately, we can deal with cases where the player manages to produce two or more chop inputs before the Network Command has travelled to the Authority (and back) with a result.
Imagine: the tree has 1 energy. If we didn't subtract energy locally, the player would be able to chop several times because until the Authority tells them that the tree is down, they still think it has 1 energy.
In fact, it would send several Chop()
Network Commands for no reason, which the Authority would have do discard on arrival.
Instead, if we immediately change the value on the variable and we use it as an indication of whether we can chop or not this will stop the chopping after one hit, as it should be.
Soon, the Authority will have elaborated on its side that the tree has gone down, and will inform our Client (with ChangeState()
). Because energy
is a synced variable, it will be overwritten again with the value computed on the Authority - which of course will be 0 at this point, so it will match.
So nothing is lost and no state is compromised, but with this little trick we get immediate feedback and we avoid some unneeded network traffic.
Advanced networking concepts
Once you have learned the basics using the tutorial project, Campfire is the natural follow-up to get acquainted with more advanced and practical topics.
As with First Steps, you can download the whole Campfire Unity project and explore it at your own pace. Instead of being a series of independent scenes, Campfire is one big scene that presents multiple concepts working together at the same time. We recommend using the pages on this section as guidance on the individual topics, starting with getting acquainted with the .
The Unity project can be downloaded from its . The Readme will tell you the minimum Unity version to use.
To quickly try out the game, we shared a WebGL build on the . You can play it directly in the browser, or download one of the available desktop versions. Share the link with friends and colleagues, and try it together!
To play as a regular Client, make sure that the GameObject called Simulator is disabled in the scene Main:
Without it, the game will behave as a pure Client and spawn a player character on connection.
If you want to make a game build, simply having that object off will produce a Client build. You can run many Client builds to experience multiplayer gameplay.
First, enable the Simulator GameObject in the scene.
Now press Play and connect.
The robot will start acting, exactly like it would do if it were running on a Simulator (minus, of course, the network delay). This allows you to see what would be happening on the server, with the full debugging power of the Unity Editor.
You can even use this Editor instance running alongside one or more Client builds.
To create a Simulator build, you have two ways to go about it, as usual:
building a Simulator to launch locally on your machine
building one to upload on the coherence Cloud
In both cases, make sure that the Simulator GameObject is enabled in the scene.
Don't change the Keeper Robot's Simulate In property like described in the previous section, since to run this behavior on the Simulator we want it to stay Server Side.
| Flexible authority
Even when creating a game that is mainly client-driven, we can still run some of the code on a Simulator. This is very useful to create, for instance, an NPC that operates even when all Clients (players) are disconnected, to give a semblance of a living world.
In this project we used this pattern for the little yellow robot that sits beside the camp. If players move one of the camp's key objects out of place, the robot will tidy up after them. It can even recreate burned objects out of thin air!
Because this behavior is run by a Simulator, even if no-one is connected, given enough time all objects will be back in their place.
To setup the robot Prefab to be run by a Simulator couldn't be simpler. The only thing we need to do is to set the Simulate In property of the CoherenceSync
to Server Side.
We also set both the KeeperRobot
script and the NavMeshAgent
to disable on remote instances from the coherence Configuration panel, so they automatically turns themselves off on Client machines.
Note that the GameObject named "Simulator" is disabled by default in the demo scene. When creating a Simulator build, you need to enable it before building, or the robot won't appear in the Simulator (and hence, on Clients).
Besides the simple state machine code that runs it, only one thing is worth noting here.
The exact moment when the robot starts acting is not in Start
like usual. We imagined this behavior for an always-on world, so that it could start acting even long after other Clients disconnected. To ensure this, we hook into the onLiveQuerySynced
event of the CoherenceBridge
:
This way, the Simulator has the time to sync up with whatever happened to the campfire objects on the Replication Server, before even beginning to act.
This means that while gameplay can benefit from the presence of this NPC, it's not dependent on it. The Simulator can be always online, or connect and disconnect at times, or to be online only at certain times of the day, and so on.
Coding behaviors like this can open up many creative possibilities in the game's design.
One typical pattern here is to wrap any server-side logic in the conditional compilation directive #if COHERENCE_SIMULATOR
. This is a great idea especially if the code needs to be obfuscated to normal Client builds, because by doing so, it won't be compiled in the Client at all.
We did it, but we were careful to leave some things out:
As you can see, we left out the 4 Network Commands used to play sounds, and the properties they need to do it. The idea here is that the authoritative instance of the robot, which is running the logic on the Simulator, instructs the non-authoritative instances to play sounds when needed.
Remember that disabling a script only prevents Unity functions to be called (Awake
, Start
, Update
...), but it doesn't prevent invoking its methods.
Besides the above, wrapping synced variables or Network Commands inside a pre-compiler directive would hide them from coherence schema baking, effectively creating a different schema for the Simulator, which would then not be able to connect to the RS.
Make sure you keep all data of this type out of the #if
, so that both Client and Simulator bake the same schema.
Finally, you might have noticed how we not only compile this code for Simulator builds, but also when in the Unity editor:
This allows us to quickly test the behavior of this robot without adding and removing compilation directives. By simply changing the Simulate In property of the CoherenceSync
to Client Side, we can hit the Play button and see the robot move, as if a Simulator was connected.
This is a great way to speed up development and one of the advantages of coherence's flexible authority model: you don't need to code a behavior in a special way to change it from Client to Server side and vice versa.
It is good practice though to switch the robot to Server Side again at regular intervals, and test the game by making an actual Simulator build, in order to create the whole network scenario with all its actors.
This will help locate bugs that have to do with timing, connection speed, authority transfers, etc.
Object lifecycle | | Runtime Unique IDs
In many cases, creating and destroying GameObjects like usual will be enough. Just call Instantiate()
or Destroy()
, and coherence takes care of instantiating and destroying the appropriate Prefab instance on each connected Client.
However, there are moments when it makes sense to customize how exactly coherence does this. To take full control over the lifetime of the object, or to attach custom behavior to these events.
coherence provides by default (and we use one too), but for ultimate control we also have the ability to create new, completely custom ones.
The campsite in this demo has a few pre-placed unique objects in the scene, that can be picked up, moved, and burned on the campfire.
Until the comes in and recreates them, they will not be replaced.
When we burn them, we could in theory just destroy the instance. However the burn code is deeply nested in the Burnable.cs
class which is used not only by these unique objects, but also by the pooled and non-unique wood logs.
In this method we do this:
However, by default unique network entities also get disabled, not destroyed. This doesn't work for our special objects!
We could potentially add an if
statement in the GetBurned()
above, detect if the object being destroyed is a log or not, and act differently based on that. Or subclass the Burnable
and implement overrides for GetBurned
...
... or we can just create a custom instantiator, and take full control of the object's lifecycle. Let's see the code.
Creating a custom instantiator is trivial. We just need a class to implement the interface INetworkObjectInstantiator
, like so:
The key parts of this script being that on network entity creation a simple Object.Instantiate()
is performed, and on release Object.Destroy()
. The other methods (omitted here) are actually empty.
We also want to prepend the class with the DisplayName
attribute so it shows up in the dropdown when we configure a CoherenceSync
. Now the UniqueBurnableObjects instantiator appears alongside the others in the Instantiate via dropdown:
That's it, the instantiator is ready to use.
When we call ReleaseInstance()
now, it will act differently depending on which instantiator the Prefab is configured to use: the wood logs get disabled, but the unique campfire objects get destroyed.
This was a very simple use case for customization, but it illustrates how easy it can be to get in control of the lifetime of Prefab instances associated to network entities.
One interesting thing we do with anchors is that they are themselves unique objects, but because they are spawned at runtime, they need to get their unique ID dynamically at runtime.
The code is in the PersistentObject
class:
We take the ManualUniqueId
from the object spawning it (i.e., "Boombox"), and we combine with the string "-anchor" to create a new unique ID, "Boombox-anchor". We register this ID to the UniquenessManager
of the CoherenceBridge
to inform it that the next spawned network entity will have that ID. And then we simply call Instantiate()
.
Because they are set to be Persistent, even though a player has burned something and disconnected, the anchors stay on the Replication Server. When a Simulator connects it will find these placeholders and, thanks to the synced properties, will know exactly what to recreate and where to put it.
The check code is in KeeperRobot.cs
, under CheckAnchors()
and ActOnAnchor()
.
First, each anchor's isObjectPresent
property is used for a quick scan. This property is synced.
If the object is still present, the robot needs to get a reference to it. It calls GetLinkedObject()
on the anchor, which does this:
Once again using the UUID of the object this anchor is a placeholder for (holdingForUUID
) as a key, we can now ask the UniquenessManager
to retrieve an object that has that UUID.
With a reference to this, the robot can now put it back into place using the anchor's position and rotation as a reference.
And if the object has been destroyed (isObjectPresent
is false), the robot proceeds to recreate it.
After that, like we saw before, the robot registers the newly recreated object with the UniquenessManager
so that it has the same UUID that it had before being burned.
The object is reinstated, and to a new Client connecting, it will look exactly the same as if it never got removed.
Before we dive into the networking-specific topics, in this introductory page we'll quickly go over how the whole gameplay is structured and set up. We'll cover it both from a point of view of Prefabs and of code so you know where to look for what.
WASD: Move | Shift: Sprint | Spacebar: Jump | E: Pick up/throw, Chop trees, Sit/stand | C: Random appearance | 1: Wave emote | 2: Dance | 3: Yes emote | 4: No emote | Enter: Show chat/send message | Esc: Cancel chat
Left stick: Move | Left trigger: Sprint | Button south: Jump | Button west: Pick up/throw, Chop trees, Sit/stand | Button east: Random appearance | D-pad up: Wave emote | D-pad down: Dance | D-pad left: Yes emote | D-pad right: No emote | Select button: Show/hide chat | Start button: Send chat
You'll find the Player Prefab in Prefabs/Characters
.
When connecting, an instance of the Player is instantiated in the scene by the PlayerHandler
script, which listens to the corresponding event fired by CoherenceBridge
.
The player character is a Rigidbody-driven kinematic capsule that is hovering above the ground slightly, and detecting the ground via a raycast. Movement values are provided by the Move
script on its root, which is in turn informed by the PlayerInput
component. When instantiated over the network both these components are disabled, and the Rigidbody is set to be kinematic.
Besides movement, other actions are controlled by scripts on three child GameObjects: Interactions, Emotes, and Chat.
When pressing the interaction key, the right action will be carried on by one of the scripts ChopAction
, SitAction
, and GrabAction
, depending on the type of the object highlighted (a ChoppableTree
, a Chair
, or a Grabbable
).
The trees have an Interactable
script that indicates which mesh gets highlighted.
They have an amount of energy that determines the number of times they need to be chopped to be cut down. When they run out, they transition to a chopped state and spawn a tree log. A coroutine makes them spring out again after a certain amount of time.
The campfire is at the center of this demo. Players can burn anything they can pick up by simply throwing the object into it. The campfire exists only in one instance and is pre-placed in the scene, and marked as unique on the network by setting the Uniqueness property of its CoherenceSync
to No Duplicates.
Most of the logic of the campfire is in the Campfire
component. This handles a lot of the networking flow, and can be run by a Client but, if a Simulator connects, they will take over.
They are all Prefab Variants of a base Prefab called Base_BurnableObject, which you can inspect to get a sense of the common functionality.
The objects have several scripts: Grabbable
provides the ability for them to be picked up, carried and thrown, while Burnable
grants the ability to be burnt on the campfire.
They have a collider at the root which determines collisions, but a child GameObject named Interaction (and its Interactable
script) has the trigger collider that makes it interactive, and allows to pick the object up. The Interactable
script also holds a reference to the objects to highlight when the player's interaction trigger intersects the object.
The Keeper Robot is an NPC designed to be run by a Simulator (aka, the "server"), to restore the campsite to its initial state even when no-one is connected.
Its script will cycle through all unique campfire objects every X seconds. If an object has been destroyed, it will recreate it and put it in its place. If it has been moved, it will just chase it down and put it back into its place.
Sitting is one of the three actions that can be performed by interacting with objects. It doesn't have networking effects, so it's not covered in this tutorial pages.
You will find the code of chairs in Chair.cs
, located in Scripts/Objects
. Looking into it, we find the property used as a gate:
Check the Log prefab in Prefabs/Interactive/Burnable/
:
This Sync Config can be found in the coherence/
folder, and is a sub-object of another ScriptableObject: the CoherenceSyncConfigRegistry
.
This is in a way similar to . The event flow is very similar:
Right now, we are looking at things in the context of a setup where Authority on the campfire is on one of the Clients. It is totally possible to give the Authority to a Server (and in fact we do in this project, see of this page), but the actual logical process doesn't change at all.
For more info on CoherenceSyncConfig
check out .
For more info on CoherenceSyncConfigRegistry
check out .
So, as long as a Simulator is connected, the campfire will keep burning
In this project, there is an NPC that is supposed to be controlled by the Simulator (the ). Though this is intended to be a server-side behavior, you can actually make it run locally and play as a player at the same time without modifications to the code.
Secondly, open the KeeperRobot prefab contained in Prefabs/Characters
. On the CoherenceSync
component, change its Simulate In property to Client Side.
For more information, refer to the .
By just doing so, when you start the game as a Client, the robot GameObject will be deactivated. But if starting as a Simulator (instructions are ), it will run.
The code for the robot is all contained in the KeeperRobot.cs
class, in Scripts/Robot
.
A simple ReleaseInstance()
does the trick for the logs which are non-unique objects. They just go back into the .
If you're curious about this code, you can check out the file in the coherence package folder in io.coherence.sdk/Coherence.Toolkit/CoherenceSyncConfigs/ObjectInstantiators
and open DefaultInstantiator.cs
API Reference for INetworkObjectInstantiator
can be found .
The first time these special unique objects come online, they spawn a persistent invisible object we call "object anchor". This object holds the original position and rotation of the object, so that the can come in at a later time and put the recreated object back into its place. You could think of these objects as placeholders.
Using the anchor's syncConfigId
as a key, it looks in the CoherenceSyncConfigRegistry
and finds the archetype to recreate. This is similar to how we used the registry as a catalogue .
When approaching an object that can be interacted with, the InteractionInput
script does the work of detecting objects that have an Interactable
script, and highlights them by changing their layer. This makes them render with an additional outline, as per one of the passes in the URP Renderer Renderer_WorldUI, contained in Settings
.
The chat system is described . Other actions are described below.
The Player Prefab builds on the structure and functionality of the one used in the , adding more actions. If you find it complex to dive into, try exploring that version first.
The prefab for the interactive tree is in Prefabs/Interactive
. The log that is spawned by it is in Prefabs/Interactive/Burnables
.
Read more about how characters interact with remote trees in about dealing with a non-authority object.
The campfire Prefab is in Prefabs/Interactive
.
In addition to calculating which fire effect to display, it's also in charge of replicating the sound of burning an object on all Clients (read more about effects ).
Learn more about the campfire's logic .
All non-static interactive objects are in Prefabs/Interactive/Burnables
.
The logs that are spawned when chopping down trees are not unique, and they are set to Allow Duplicates. Check for more info on the logs and how they are recycled using an object pool.
Instead, the other burnable objects are pre-placed in the scene, and set to be unique (No Duplicates): the banjo, the cooler, the bins, the mushrooms, and more. More details on the lifetime of these pre-placed objects in .
You'll find the robot Prefab in Prefabs/Characters
.
The way the robot knows about destroyed objects is because the objects, when created the first time, spawn an invisible marker (that we call an "object anchor") which the robot can inspect to know which object has disappeared, and where it was originally placed. The page about has more info on these objects and their anchors.
Read more about this server-side NPC works on its.
You will find chairs in Prefabs/Interactive/Chairs
.
Networked audio | Networked particles | Animation Events
Usually, visual feedback can be expressed via syncing variables like Animator parameters, positions, and rotations. But sometimes we have the need to play sounds and particles, which are not types that can be automatically set to sync, or that we can send as arguments of Network Commands. So how to do it?
This project has a lot of moments where particles and sounds need to play, and we used different strategies for different cases, depending on how fast, repeated, or slow the action is.
The most straightforward solution to play a sound is to use a Network Command. Using Commands, you can remotely invoke methods on AudioSource
or ParticleSystem
components.
To do that, you could simply open the coherence Configuration panel (from the CoherenceSync
), and check the methods you're interested in.
While this is a perfectly fine way of doing things, it requires you to call multiple Network Commands in case you wanted to play a sound and particles at the same time. This could lead to desynchronisation between sound and visuals.
As such, in this project we preferred compacting these calls into methods on their own that are invoked as one Network Command, often without parameters to minimize the data being sent across.
Connected to the above, let's see how to create our own Network Commands to play sounds (or particles) as a result of an event that happened remotely.
For instance, the Keeper Robot has a series of voices that play whenever it is performing an action. The robots is always controlled by the Simulator, so we need to play sounds on the Clients' devices.
For these sounds, we isolated the sound-playing behavior into Commands of their own. At the end of the KeeperRobot.cs
class, we have:
(soundHandler
is a script attached to the same gameObject)
Each of these methods is invoked as a Network Command, like so:
You can see how we don't play the sound over the network, that would be bandwidth-consuming for no reason, but we just communicate the intention to play it.
Because we only have 4 sounds, we sort of "brute-forced" this, and created an individual Network Command for each sound. This is not a bad idea from the point of view of network traffic: sending a Network Command with no parameter produces less traffic than sending one with.
But it could be unwieldy if we had - say - 100 different sounds to play.
This solution also requires us to bake and produce a new schema if we add or remove one of these Commands. So for a more flexible solution, it could be nice to index the sounds and maybe create a generic Command like:
In this case though, it was ok to go for individual Commands.
There are actions that are really quick or short, and asking to play a sound via a command might result in a mismatch between the visuals (an animation) and the sound, due to network delay.
For instance, it wouldn't make sense to send a Command to inform other Clients to play the sound of a footstep. Chances are, by the time they receive the Command, another two-three footsteps have happened.
So for footsteps, jump, landing, and more; we used a slightly different strategy. Audio and particles are all played locally as part of the animation, using Unity's own Animation Events.
A script called PlayAnimationEvents.cs
(remember to add it to the same object as the Animator
!) listens to these events. An example from it:
This ensures an immediate playback, in sync with the animation. Plus, it produces zero network traffic.
So yes, fun fact: to "network" sounds and particles often you can do without networking anything at all!
One more trick! If you have a state machine blending several clips, you might hear multiple overlapping sounds when a transition happens. One less known trick is to measure the weight of each clip while executing Animation Events, like we do below:
Chat | Lobbies
Communication is an inherent part of online games and a chat, however simple, is a great way to enhance the range of expression for the players.
We wanted to implement a very simple chat system. By pressing Enter, a small screen-space UI opens up and allows the player to compose a message. When they press Enter again, a balloon on top of their character displays the message to them, and to all connected Clients.
This is done in three parts.
The Chat
script on the player reads the input, requests ChatComposerUI
to display the chat composer that is part of the screen-space scene UI.
When the player sends a chat message, Chat
is informed by an event sent by ChatComposerUI
, and sends a Network Command SendChatMessage
to all other clients.
Finally, the received message is displayed in world-space over the player's head the script ChatVisualiserUI
present in the Player Prefab.
By default, coherence's Network Commands have a limit in the length that can be sent in one command. This is limited by the length of a UDP packet. While this limitation might be removed in the future, for now it means that chat messages can't be longer than a certain amount.
This amount, however, is quite different depending if you use a parameter of type string
or of type byte[]
(byte array). If you send a string
, you will be able to pass on around 50 characters. This is really not much for a chat system.
If you use byte[]
though, the number of characters goes up to (around) 500. Now we're talking!
So what we do in this demo is that first we convert the string
that the player has typed in the UI into a byte array, and we send that via Network Command:
Then, on the receiving side, we reconvert it back into a string
:
This simple trick allows us to send longer messages, or to send the same message generating less traffic.
Because we are sending the chat messages on the CoherenceSync
that is on the Player Prefab, it means that if that particular player instance is not visible to a Client because it's outside of their LiveQuery, they won't receive the Network Command and thus the chat message. This is maybe desirable in this demo, where the chat is visualised on top of the player.
But if chat messages are shown in a UI panel and players should receive them all regardless, then it might make more sense to rely on a special type of CoherenceSync
: Client Connections. By sending the Network Command on that, it would ensure that the Command is sent and received regardless of LiveQuery ranges.
Read the Client Connections page for more info.
This page talked about a simple chat system to use during gameplay, but keep in mind that coherence also has a solution for long-form chats as part of Lobby rooms. Players can be in a lobby before but also during gameplay.
For more information about Lobbies, read the specific page.