How to create a multiplayer racing game in Unity (Part 2)

Peter Z
3 min readJun 25, 2019

--

In the first part of the tutorial, We installed the SWNetwork SDK and converted the Vehicle GameObject to a Networked GameObject.

In this post, we are going to use RoomPropertyAgent to implement starting and winning logic of the race.

Starting and timing

We can use an Integer SyncProperty to keep track of how many players have pressed the Enter key and make the game start when all players in the room have pressed the Enter key.

  1. Add a RoomPropertyAgent to the FinishLine GameObject and set the Agent Id to 1.
  2. Add a Game Sync Property and name it PlayersPressedEnter.
  3. Set its Type to Int.
  4. Set its Conflict Resolution to Custom.

By using the Custom conflict resolution rule, SWNetwork will invoke the OnConflict event when conflicts occur. In our case, we just need to add 1 to the remote PlayersPressedEnter value to resolve the conflict. The workflow looks like this:

Next, we need to modify the GameSceneManager.cs script to implement the event listeners of the PlayersPressedEnter SyncProperty.

When setting the event listeners, make sure to select the OnPlayersPressedEnterValueConflict method in the Dynamic section of the methods list.

The RoomPropertyAgent settings look like this:

Now, both players should start at about the same time.

Winner

The player who finished all the laps first is the winner of the game. We can use a string SyncProperty to store the PlayerId for the winner.

  1. Add a Game Sync Property and name it WinnerId.
  2. Set its Type to String.
  3. Set its Conflict Resolution to Their.

By using the Their conflict resolution rule, SWNetwork uses the remote value to resolve conflicts of a SyncProperty. This works perfectly in our case as we don’t want to override the WinnerId once it is set. The workflow looks like this:

Next, we need to modify the GameSceneManager.cs script to set the WinnerId SyncProperty to the player who completed the laps first.

The RoomPropertyAgent settings look like this:

Summary

That’s it for this tutorial. Congratulation! You now have a multiplayer racing game that is ready to share with friends to play together, and you’ve learned a lot about the SocketWeaver SDK for Unity.

The full source code of the tutorial is hosted on Github. Please feel free to modify it to fit your game. https://github.com/SocketWeaver/karting

If you have any questions, suggestions about the tutorial or our SDK for Unity, join our Discord server https://discord.gg/qXt7Bkf. Our engineers will be happy to help you!

Thanks for reading!

--

--