How To Register A Handler Unity Networking C#
If you've been making games with Unity for some time, you know in that location's a lot of difficult work that goes into creating a game. Things such as level design, game mechanics, and progression take a lot of trial and error and careful design to get correct. Even so, only a limited number of people are able to complete a full game.
Compared to that, multiplayer games such as Fortnite and PUBG take taken the world by storm. These games, which are easy to learn but hard to master, keep getting more and more than popular with a record-breaking number of people. Some people even brand a career out of these games every bit Twitch streamers, something that is very difficult to do with unmarried actor games.
In this tutorial, you'll learn how to make your own multiplayer game with Unity and the Photon Unity Networking library (PUN for short).
Specifically, you'll learn:
- The central differences betwixt Unity Networking and PUN.
- How to create a Entrance hall scene where players tin can join.
- How to load the game scene and synchronize the Transform values of players.
Let'due south get started.
Photon vs Unity — Which is better?
Before getting on to the tutorial, allow'southward have a wait at the central differences betwixt Unity Networking and Photon Unity Networking.
Exploring the Architecture
Both Unity and PUN accept similar low-level APIs. Simply the architecture required for these libraries to employ these APIs is the central differentiating factor between them.
Source: https://world wide web.youtube.com/watch?five=xLECRl1eyGk
The above diagram depicts how messages are transferred between nodes in a network in Unity and in PUN.
Unity Networking supports a server/client architecture. All letters take to get through the Host customer and can't be sent directly betwixt nodes. For example, based on the diagram above, messages transmit from client B to client C using the post-obit path: Client B ▸ Relay Server ▸ Host A ▸ Relay Server ▸ Client C.
As you can see, the message takes a total 4 hops from source to destination. In addition to this, if the Host gets disconnected from the network, the game stops.
PUN has a similar server/client architecture, but as well supports peer-to-peer sending of messages. For example, based on the diagram above, messages transmit from Client B to Client C using the following path: Client B ▸ Relay Server ▸ Client C.
That's a total of ii hops compared to the 4 in Unity for the same message transfer between two nodes. In addition to this, PUN could potentially featherbed the Relay Server entirely and Customer B can communicate straight with Client C, thus reducing the hops to 1.
Because of this, PUN is faster than Unity.
Pricing
Another key difference between Unity and PUN is the Pricing model.
Unity offers a costless number of Concurrent Users (CCU) for each license.
- Personal: twenty Concurrent Users
- Plus: 50 Concurrent Users
- Professional: 200 Concurrent Users
If you need to increase the number of CCUs that your game supports, yous'll have to pay for the extra bandwidth that you utilize. Yous'll be charged $0.49/GB of traffic that travels through the Unity infrastructure (Matchmaker and Relay Server).
Source – https://support.unity3d.com/hc/en-us/articles/209604483-How-much-does-Unity-Multiplayer-cost-
PUN also provides up to 20 CCU, 8000 Monthly Actives and 500 Messages per room for Complimentary. In addition to the free plan, information technology offers a very prissy $95 i-fourth dimension payment option for 60 Months, which includes 100 CCUs, 40k monthly actives, and 500 letters per room. This choice is great for small indie developers who are on a budget.
The combination of comparably faster performance, well written tutorials and documentation, and a healthy choice of pricing plans make PUN a very expert option for developers to build multiplayer games.
Pricing – https://www.photonengine.com/en-United states/PUN/pricing
Getting Started
You'll demand Unity version 2018.3 or newer to load the starter project successfully. In instance y'all don't have information technology installed on your system, you tin can download it from unity3d.com.
Note: This tutorial is intended for users with basic scripting knowledge and who are comfortable with the editor. If you're new to Unity, y'all can check out our beginner tutorials at https://www.raywenderlich.com/unity
Once you take everything ready upwards, download the starter projection using the Download Materials link at the top or lesser or this tutorial, and open Photon Starter with Unity.
Project Overview
Take a wait at the folder structure in the Project window:
Here'southward what each folder contains:
- LogViewer: Files required for the LogViewer asset.
- Materials: Materials required for this tutorial.
- Models: Models required for this tutorial.
- Photon: Files required for the Photon Library.
- PhysicsMaterial: Physics Materials used in the project.
- Prefabs: Prefabs for the tutorial.
- Resource: Prefabs that accept to be synced by Photon.
- Scenes: The game'south Chief Carte du jour and Loonshit scenes.
- Scripts: The scripts required for the project.
Open the Launcher scene from Assets / RW / Scenes.
If you lot've played multiplayer games before, yous'll know that before you and your friends commencement playing the game together, you first need to create or join a Entrance hall (or a Game Room) where you all connect and then the foyer leader initiates the game.
In this scene you'll make a Vestibule using Photon Unity Networking. Y'all'll create a Room with a specific name, and then your friend can join your lobby past entering the same room "name" in their instance of the game.
Once you and your friend have joined the aforementioned room, the foyer leader can load the MainArena scene, where you lot both can play the game together.
Creating a Photon Account
Before you go started with building the Lobby, you lot'll need to create an account at the official site of Photon Engine by going to https://dashboard.photonengine.com/en-us/account/SignUp.
- Once you've successfully signed upwards, you'll be redirected to your business relationship Dashboard.
- On the aforementioned page, click on the Create a new app button. Enter a name for your app, "SampleApp" for example, and click on the Create push button at the bottom of the form.
- Finally, on the Dashboard page, you'll run across a box with the details of your "SampleApp". Re-create the AppId and store information technology somewhere, as you'll apply this subsequently on in the tutorial for testing.
Note: The Photon Unity Networking library is already nowadays in the starter projection you downloaded at the beginning of this tutorial, but you can also use it in your existing projects by downloading the unitypackage from the Asset store.
Back in the Unity Editor, open the PUN Wizard by selecting Window ▸ Photon Unity Networking ▸ PUN Sorcerer.
In the PUN Wizard window, click Setup Project and enter the AppId that you saved while setting up a photon engine account in the previous department. Click the Setup Project button.
At present that yous have Photon set upwards, permit's go started with building the Foyer.
Creating the Lobby
Here'south an overview of what the Launcher.cs script is going to do, in social club:
- Connect to the Photon Network.
- Once connected, take 2 inputs from the user: The Player Proper noun they want to use, and the Room Name they want to Create or Join.
- If a Room with the entered name doesn't exist, create a Room with that name and make the electric current actor the Lobby Leader. If the Room exists, the player will join the Room.
- One time both players have connected to the same room, the Anteroom Leader can load the MainArena scene.
Open the Launcher.cs script in Assets / RW / Scripts.
Add the following lines of code in Launcher.cs afterwards the comment // Get-go Method
.
Don't worry most the intermediate errors while adding the code. All the necessary code will exist explained in sections below.
// Kickoff Method void Starting time() { //1 PlayerPrefs.DeleteAll(); Debug.Log("Connecting to Photon Network"); //two roomJoinUI.SetActive(false); buttonLoadArena.SetActive(imitation); //3 ConnectToPhoton(); } void Awake() { //4 PhotonNetwork.AutomaticallySyncScene = true; }
Hither's a brief explanation of the lawmaking.
- When connecting to a server, PUN pings all available servers and stores the IP address of the server with the everyman ping as a
PlayerPrefs
central-value pair. This can lead to unexpected beliefs during the connection stage. To avoid any anomalies,DeleteAll
is chosen when the Launcher scene starts. - The UI elements are hidden by default, and are activated once a connection to a Photon server is established.
-
ConnectToPhoton
is called to connect to the Photon network. - The value of
AutomaticallySyncScene
is prepare totrue
. This is used to sync the scene across all the connected players in a room.
Loading the MainArena Scene
To get the Input from the TextField UI elements, you need a public method to shop the value in a TextField. Add together the following code after the annotate // Helper Methods
:
// Helper Methods public void SetPlayerName(string name) { playerName = proper noun; } public void SetRoomName(cord name) { roomName = proper noun; }
Next, add the post-obit methods later on the comment // Tutorial Methods
:
// Tutorial Methods void ConnectToPhoton() { connectionStatus.text = "Connecting..."; PhotonNetwork.GameVersion = gameVersion; //i PhotonNetwork.ConnectUsingSettings(); //2 }
How this lawmaking works:
- The
GameVersion
parameter is set. This is the version cord for your build and can be used to divide incompatible clients. For this tutorial, it will be set to 1 (set up when thegameVersion
field is declared). -
ConnectUsingSettings
is called, which is used to connect to Photon as configured in the editor. Y'all tin read more in the docs.
Side by side, add the post-obit lines of lawmaking:
public void JoinRoom() { if (PhotonNetwork.IsConnected) { PhotonNetwork.LocalPlayer.NickName = playerName; //1 Debug.Log("PhotonNetwork.IsConnected! | Trying to Create/Bring together Room " + roomNameField.text); RoomOptions roomOptions = new RoomOptions(); //2 TypedLobby typedLobby = new TypedLobby(roomName, LobbyType.Default); //3 PhotonNetwork.JoinOrCreateRoom(roomName, roomOptions, typedLobby); //four } } public void LoadArena() { // v if (PhotonNetwork.CurrentRoom.PlayerCount > 1) { PhotonNetwork.LoadLevel("MainArena"); } else { playerStatus.text = "Minimum 2 Players required to Load Arena!"; } }
Looking at each line of code comment-past-comment:
- The
NickName
parameter of theLocalPlayer
is set from the individual variableplayerName
. This is the name that volition be bachelor to anybody you lot play with on the Photon network, and is used as a unique identifier. - An object of class
RoomOptions
is alleged. This wraps up common room properties required when you create a room. It tin be used to give the user control of diverse characteristics of the room such as maximum number of players that tin can join, PlayerTtl (Histrion Time To Alive), etc. (Docs) - An object of grade
TypedLobby
is declared. This refers to a specific lobby type on the Photon server. The proper noun and lobby type are used as an unique identifier. The Room name is set from the individual variableroomName
and the Lobby type is set asDefault
. (Docs) - Finally, the
JoinOrCreateRoom
method of PhotonNetwork course is called with arguments —roomName
,roomOptions
andtypedLobby
that were fix earlier. If the method is called by a new user with a new Room proper noun that does not yet exist, a room is created and the user is set equally the Lobby Leader. Otherwise, the other players merely join the room. - Once the Lobby Leader has created and joined a Room, the LoadArena push will exist fix agile. A cheque is set before loading the Arena to make sure the MainArena scene is loaded only if both players take joined the room.
PUN Callback Methods
At present that yous've added the basic building blocks of Joining and Creating a Room, all that's left to do is add PUN Callback methods that will take care of the exception handling.
Add the following lawmaking afterwards the comment // Photon Methods
:
// Photon Methods public override void OnConnected() { // 1 base.OnConnected(); // 2 connectionStatus.text = "Connected to Photon!"; connectionStatus.color = Color.green; roomJoinUI.SetActive(true); buttonLoadArena.SetActive(simulated); } public override void OnDisconnected(DisconnectCause crusade) { // 3 isConnecting = false; controlPanel.SetActive(true); Debug.LogError("Disconnected. Please check your Net connectedness."); } public override void OnJoinedRoom() { // 4 if (PhotonNetwork.IsMasterClient) { buttonLoadArena.SetActive(true); buttonJoinRoom.SetActive(simulated); playerStatus.text = "You are Lobby Leader"; } else { playerStatus.text = "Connected to Lobby"; } }
Let's expect at what each piece of code does:
- As the name suggests,
OnConnected
gets invoked when the user connects to the Photon Network. Here, the method calls the base methodonConnected()
. Any additional code that needs to be executed is written following this method call. - These methods provide feedback to the user. When the user successfully connects to the Photon Network, the UI Text
connectionStatus
is gear up, and theroomJoinUI
GameObject is set to visible. -
OnDisconnected
gets chosen if the user gets Disconnected from the Photon Network. In this example, thecontrolPanel
GameObject is ready tofalse
, and an Mistake type bulletin is logged to Unity. - Finally,
OnJoinedRoom
is called when the user joins a room. Here, it checks if the user is the Master Client (the first user to bring together the room). If so, the user is set as the antechamber leader and is shown a message to indicate this. The lobby leader has the power to load the MainArena scene, which is a common fashion of creating a room in most pop multiplayer games. Otherwise, if the user is not first to bring together the room, a message is shown to tell that user that they've successfully joined the room.
Save the Launcher.cs script and head back to the Launcher scene, and click Play.
Equally you can see, when the Scene starts, ConnectToPhoton
gets called and the Connection condition UI Text shows "Connecting…". Once successfully connected, the text changes to "Connected", and the visibility of the roomJoinUI GameObject is set to true.
Next, the user can enter their Name and the name of the Room that they want to Create or Join past clicking on the Join Room button.
Finally, if the user is the Chief Client, the playerStatus Text is set to "You are now the Foyer Leader!" and the Load Loonshit button is gear up agile. Otherwise, an indication of a successful lobby bring together is shown.
At this point you tin test joining a Room past building an executable of the project for your Operating Arrangement by selecting File ▸ Build and Run. You should be able to load the MainArena scene using both your newly built executable and the Unity Editor joined to the same room.
However, you lot can see only an empty arena with no players. In the adjacent department, you'll larn how to add player and brawl prefabs to the scene for each individual client. You lot'll also sync their Position, Rotation and more across the Photon Network.
Using the Photon Transform View Component
With the room joining code washed, the next important Photon Unity Networking concept you need to know is the Photon View Component.
PUN makes it very easy to make a Prefab whose backdrop (Position, Rotation, etc.) accept to be synced across the network during a multiplayer game using the Photon View Component.
An important concept to sympathise about using PUN is that a Prefab that should become instantiated over the network has to be inside a folder named Resources.
An of import side consequence of having Prefabs inside Resources folders is that you need to lookout their names. Y'all should not accept two Prefabs nether your Avails' Resources paths named the aforementioned, because Unity will simply pick the first 1 it finds.
With that out of the manner, let'south get started building the Game Director.
Open the GameManager.cs script in Avails / RW / Scripts.
Hither's an overview of what the GameManager.cs script is going to practise:
- When the MainArena scene is loaded, bank check whether the client is the Principal or not. If they are, Instantiate the
Car
GameObject usingPhotonNetwork.Instantiate
, change the name ofplayer1
GameObject and also Instantiate theball
GameObject. Otherwise only Instantiate theplayer2
GameObject and modify its proper noun. - Add together a PUN Callback method that will take intendance of various use cases based on network conditions and events.
- Helper methods will Disable UI, Quit Room, etc.
Add the following code afterward the comment // Start Method
:
// Start Method void Start() { if (!PhotonNetwork.IsConnected) // 1 { SceneManager.LoadScene("Launcher"); return; } if (PlayerManager.LocalPlayerInstance == goose egg) { if (PhotonNetwork.IsMasterClient) // 2 { Debug.Log("Instantiating Role player i"); // 3 player1 = PhotonNetwork.Instantiate("Car", player1SpawnPosition.transform.position, player1SpawnPosition.transform.rotation, 0); // 4 ball = PhotonNetwork.Instantiate("Brawl", ballSpawnTransform.transform.position, ballSpawnTransform.transform.rotation, 0); ball.name = "Ball"; } else // 5 { player2 = PhotonNetwork.Instantiate("Motorcar", player2SpawnPosition.transform.position, player2SpawnPosition.transform.rotation, 0); } } }
Here's how this works:
- Check whether the client is continued to the Photon Network or not. In case at that place are some issues with the network, then the Launcher scene should become loaded and so that the customer tin can try to connect once more.
- Get a reference to the local Thespian (the player that is controlling the client), and check whether information technology is the Master client.
- If information technology is, Instantiate the Player GameObject from the Resources folder (which y'all will exercise in the next stride) using the
PhotonNetwork.Instantiate
, and relieve a reference to it in theplayer1
GameObject. - Similarly, Instantiate the
Ball
GameObject so that information technology's the aforementioned Brawl GameObject that'south loaded on all clients connected to the current room. - If the client is non the Master, load the
Player
GameObject from the Resource folder and save a reference to information technology in theplayer2
GameObject.
Salve the file and get back to the Editor.
Now that you accept the logic gear up to Instantiate the Player and Ball GameObjects, the next step is to add the required components so they can be Instantiated using the PhotonNetwork.Instantiate
method.
From the Project Window, double-click Car prefab in Assets / RW / Prefabs
to open it in Prefab Editing mode.
In the Inspector, yous should be able to see that some basic components for a Car GameObject (Rigidbody, Collider, Movements, etc.) are already part of the prefab.
Since merely the Transform properties of the GameObject need to exist synchronized across the network, add the Photon Transform View component to the Machine GameObject.
You'll notice that a Photon View component is also added, every bit the Photon Transform View component inherits a lot of properties from information technology.
In add-on to synchronizing the position, rotation and scale of a GameObject, Photon Transform View gives you lot many unlike options to make synchronized values appear smooth even when the information is received but a couple of times per 2d.
In the Inspector, set the Observe option to Unreliable on change in the Photon View Component. This will ensure there'south a smoothen transition between the Car Transform values.
Likewise, add the Car prefab to the Observed Components list in the Photon View component so that its selected Transform properties (seen as selected in Photon Transform View component) are synchronized.
Salvage the Car prefab.
Side by side, open the Ball prefab from Avails / RW / Prefabs in Prefab Editing fashion and repeat the in a higher place steps:
- Add Photon Transform View component.
- Set the Discover Option to Unreliable on Alter.
- Add the Brawl prefab in the Observed Components list in the Photon View component.
Finally, move the Car and Ball prefabs from Assets / RW / Prefabs to Avails / RW / Resources, then that they tin can be loaded by the PhotonNetwork.Instantiate
method.
Time to test!
Select File ▸ Build and Run to build an executable binary for your Operating System.
This time:
- Enter a different player proper noun in both clients.
- Enter the same Room name.
- Click the Load Loonshit push button from the Master client.
You should see that the MainArena scene is loaded with 2 Players (cars) and a Ball. You tin can use the WASD
or the Arrow keys
on your keyboard to move the motorcar around in the arena.
Notice only the one car moves in both clients (the car that belongs to the client).
You tin also meet that both the position of the players and the ball are synchronized in both clients.
All the piece of work is done by Photon Transform View Component that you added to the Motorcar and Ball prefabs.
However, if y'all shut one of the clients, the other client is left unstable. To handle cases like this, yous'll add callback methods to perform the necessary action based on the present situation of a client (such equally a network loss or the other player left).
Calculation PUN Callback Methods
Add the following code in GameManager.cs after the annotate // Update Method
:
// Update Method void Update() { if (Input.GetKeyDown(KeyCode.Escape)) //i { Awarding.Quit(); } }
This is fairly straightforward.
At any point in the game, if the Escape
push is pressed, call Awarding.Quit
.
Next, add the following code after the comment // Photon Methods
:
// Photon Methods public override void OnPlayerLeftRoom(Histrion other) { Debug.Log("OnPlayerLeftRoom() " + other.NickName); // seen when other disconnects if (PhotonNetwork.IsMasterClient) { PhotonNetwork.LoadLevel("Launcher"); } }
OnPlayerLeftRoom
is a PUN callback method that gets called whenever a Player leaves the room, either by closing the client or getting asunder from the network.
Finally, add the following code afterwards the annotate // Helper Methods
:
// Helper Methods public void QuitRoom() { Application.Quit(); }
When Canvas / Superlative Menu Panel / Quit Room Button
is clicked, this method will be called.
Finally prepare the On Click () event of Quit Room Push button to GameManager.QuitRoom
.
And that'south it!
Yous tin build a terminal binary for your Operating Arrangement and outset playing!
Where to Go From Here
The aim of this tutorial was to give you an introduction to the bones concepts of building a multiplayer game. You tin use these same principles to plow your existing single role player game into a multiplayer game!
You can read more nigh the Photon Unity Networking library at the official website.
If you have whatever questions or comments, or you just want to show what yous experimented with in this tutorial, join the discussion below!
Source: https://www.raywenderlich.com/1142814-introduction-to-multiplayer-games-with-unity-and-photon
Posted by: johnsonyesectood1961.blogspot.com
0 Response to "How To Register A Handler Unity Networking C#"
Post a Comment