The start of a series exploring synchronization issues in Unity and Photon through example.
As I suspect many other folks do, I thought to build my first multiplayer game as yet another Pong game. Everything went smoothly until I went to try to synchronize the movement of the ball between the two players.
Decided to step back from that project and first tackle this synchronization problem through a simplified example; documenting as I go.
Create and login to a Photon account. Create a new Photon application of type Photon PUN. Take note of its App ID; we will need it later.
Create a new Unity project based on the 3D template.
Using the Unity Asset Store, download and import Photon Unity Networking Free. We will use the App ID generated earlier to complete this step.
We, next, setup the Table scene with all the game objects; GameManager is an empty object at this point.
In order to allow the ball to bounce indefinitely, we create a Physics Material, Material, and apply it to the floor and sides.
We create a Sphere, Ball:
- In the middle of the floor
- Apply Material to it
- Add a Rigidbody component to it
- Add a Photon View component to it
- Create a prefab of it in a new folder called Resources in Assets
- Finally remove Ball from the scene
We create a script to join a Photon room on startup and add it to the GameManager game object.
We then create a script to set the ball in motion on a click and add it to the Serve game object and as the click handler for its Button component.
With this in place, we can run two instances of the application, e.g., can build a standalone application. When the second instance starts, it will join the same room as the first instance; enabling the Serve button there. Pressing the Serve button will set the ball in motion.
- When the second player connects, the first player instantiates a networked Ball, i.e., the ball is created for all players in the room.
- The Ball, however, is not setup with anything to observe; thus nothing is synchronized between the two instances of Ball.
Having everything in place, we dive into synchronizing the ball’s movement in Synchronization Issues (Unity + Photon): Part 2.