Remote interactions: Trees

Topics covered

Authority | Authority transfer | Network Commands

We saw in the previous section about sitting on chairs 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.

Our use case

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

The code

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:

[Sync] public int energy = 3;

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.

public void TryChop()
{
    if (energy <= 0) return;
    
    if (sync.HasStateAuthority)
        Chop();
    else
    {
        energy--;
        sync.SendCommand<ChoppableTree>(nameof(Chop), MessageTarget.AuthorityOnly);
    }
}

(2) On the Authority, the Chop() method is called, and checks if the tree needs to be effectively cut down based on its energy:

[Command(defaultRouting = MessageTarget.AuthorityOnly)]
public void Chop()
{
    if (energy <= 0) return;
    
    energy--;
    
    if (energy <= 0) CutDown();
}

(3) If so, CutDown() is invoked locally, spawning the log and informing all other clients to play the animation of the tree disappearing:

private void CutDown()
{
    ChangeState(false);
    sync.SendCommand<ChoppableTree>(nameof(ChangeState), MessageTarget.Other, false);

    // Spawns log
    StartCoroutine(GenerateNewLog());
    
    // Will grow the tree back in time
    StartCoroutine(GrowBack());
}

(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.

Changing a synced variable on non-authoritative Clients

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.