Photon Unity Networking Game Tutorial Part 6 – Health, Score and Nickname

Hello again and welcome to part 6 of my PUN networking tutorial. In this part, we will add score and health display, name labels and destructible tanks.


I’ve made a number of changes to the scripts from the previous part, so before you continue you should download the complete project files for this part which can be found here.

You can download the project .exe here.

Tutorial uses Unity version V2017.2.0f3



Part 6a – Nickname and name label

It would be nice if we could enter a nickname that will be shown above the tank so that we can identify our intended target, so I’ve added a text input field to the start menu where you can type your chosen nickname and a public static property in the MainMenu script which affords us easy access to the name entered.

In the Awake() function, as a convenience, we prefill the nickname input field with the previously saved nickname if we’ve logged in before (the nickname is saved to playerprefs in the JoinGame() function of the GameManager).

To enable other players to see your nickname it will need to be synchronised with all players over the network. Handily PUN comes with a built-in way to do this in the form of The PhotonNetwork.playerName property. We just need to pass the value from the NickName input field to this before we join a room and this will set the NickName property of your PhotonPlayer once created to the same value for retrieval during the game when required. This is automatically synchronized between all clients.

A convenient place to set the PhotonNetwork.playerName property is in the JoinGame() function of the GameManager script as so:-

We want to display the name of other players in the game above their tanks, so to do this I’ve added a canvas and UIText object to the player prefab to act as a name label.
A handy time to set the name label text would be in OnPhotonInstantiate, but as the name label is a child of the player prefab it won’t receive that callback. To solve this, I use BroadcastMessage in the OnPhotonInstatiate method of the Player script to call a method on all ll scripts on the player, including children. In this case, I named the method OnInstantiate. This can be quite a handy way to initialise child GameObjects as soon as the player object is created. BroadcastMessage should be used with a certain amount of care, as it isn’t a particularly fast function, and should be avoided in things like update loops. As it’s only being called once here when the player is first created it won’t affect performance.

I also took the opportunity to rename the Player GameObject to reflect the chosen nickname, as this makes it easier identifying specific clients player objects in the hierarchy.

So the Player script OnPhotonInstantiate method now looks like this:-

I also added a simple script to the name label GameObject:-

As you can see, this script implements a single method, OnInstantiate, wherein it checks to see if it is running on the local player (PhotonView.isMine) and if it is, it disables the name label GameObject because we don’t want to display the name above our own tank (we will display our own nickname at the top of the screen, as described a bit later on), otherwise, it sets the name label text to the PhotonNetwork.playerName value.

This method is invoked by the Player script when the player object is instantiated as described above.

I’ve also added a script to the name label that keeps it orientated towards the screen regardless of the rotation of the tank:-

That’s all that’s required to display the player’s nickname above other player’s tanks.

To display the nickname for the localplayer I have created a gameUI game object as a child of the HUD gameobject, which also displays the health and remaining hit points. This is the script that is attached to the gameUI gameobject:-

the gameUI script uses the SceneLoaded event to enable or disable itself depending on whether we are in a room or not. It also uses the OnJoinedRoom callback to set the NickName text to the value of the PhotonNetwork.playerName, which as described above is the nick name chosen on the main menu.

It has a couple of other public static methods which handle setting the HP text and score text.

Part 6b – Handling player damage
In the previous part of the tutorial, we didn’t synchronize the player health value over the network, as we only showed its value to the local player. However, I want to show a health bar above all players tanks and for this to be possible the player’s health value needs to be synchronised on all clients.

We’ll achieve this by making the HP value a PhotonPlayer.CustomProperty. Custom Properties are a key-value set (Hashtable) which is available to all players in a room. They can relate to the room or individual players and are useful when only the current value of something is of interest. (More info regarding CustomProperties is available from the Photon Unity Networking class reference here.)

Custom properties values are automatically updated on all clients when their value changes and an event is also raised; You can listen for this event and use it to update visual elements to reflect the new value; in this case, we’ll update the health bar on all network instances of the player’s tank and the HUD display for the local player.

To facilitate this, we’ll change the PlayerHealth.hitPoints field into a property and implement the Getter and Setter to manipulate the HP Custom Property as so:-

The getter of the property checks to see if the key exists in the hashtable of custom properties associated with the client, and if it does it returns the associated value. If it doesn’t exist, that means this property value hasn’t been set yet, so it just returns the default value.
The setter of the property updates the key/pair value in the hashtable. For the local player, this happens instantly, for other clients the new value will be sent via the Photon server so there will be a small delay.

As I mentioned earlier whenever a custom property value changes it raises an event which we can handle by overriding the OnPhotonPlayerPropertiesChanged() method which in this case we do like so:-

The OnPhotonPlayerPropertiesChanged() method is passed an array of data which contains the PhotonPlayer of the client that updated its property (in element 0 of the array) and a hash table of the updated properties and their values (in element 1 of the array), so we can use this information to take the appropriate action.

The first thing we do is retrieve the  PhotonPlayer.id of the client that updated its property and compare that with the id of the PhotonPlayer of the photonView that owns this script, and only continue if they match, this is to make sure we only continue on scripts that belong to the player that has had an updated property. Then we check that this is a message relating to a change in the hitPoints by checking if the hash table contains the key “HP”. Assuming the two previous checks are true we call a method (DisplayHealth) to handle the display of the updated hitPoints, which is implemented as follows:-

The first thing displayHealth does is update the size of the health bar above the tank by calling the healthBar.SetHealthBarValue() method ; this will happen on all clients.
Secondly we want to display the HP figure in the HUD for the localplayer only, so we wrap the call to GameUI.SetHealth() in a photonView.isMine check.

I’ve also updated the playerHealth script to check if our hitPoints have reduced to zero, so we can take the appropriate action, which in this case is to blow the tank up and add a point to the attacking player’s score. To do this we send an RPC to the missile owner that will add 1 point to their score and we start a coroutine that will handle the visual display of the tank exploding and respawning.

This is the updated PlayerHealth.DoDamage method :-

and this is the tank explosion coroutine :-

The explosion coroutine invokes the following RPC on all clients, which means that everyone sees the tank explode. It also temporarily disables movement, shooting and collisions…

it then waits 7 seconds and invokes the RPC_Respawn method, passing the respawn position and rotation as arguments. The position vector is converted to an array of 2 Shorts to reduce bandwidth.

The respawn method re-enables movement and shooting for the local player, and then for all clients it re-enables collisions and the tank model, and places it in the respawn position and orientation. It also resets the hitPoints to maximum.

The last line is a bit of a workaround to handle the fact that positioning of remote client tanks doesn’t happen instantly, so to avoid the chance of seeing them reappear in the previous position for a few frames before being moved to the new spawnpoint we wait for a short while before reenabling the tank model for remote clients.

Part 6c – Displaying the score
The final thing we need to do is make a small change to the PlayerScore script to make it display the score on the HUD of the local player which we do by calling the GameUI.SetScore() method as so:-

That’s everything for this part. As always comments and suggestions are very welcome, or if any parts require further clarification post a comment.

In the next part we’ll be adding ammo pickups, hope to see you then.

Project source files

Project executable

Tutorial uses Unity version V2017.2.0f3

Photon Unity Networking Game Tutorial Part 5 – Arming Your Tank

Hi again, as promised here is the next instalment of my networking tutorial for PUN, albeit rather a long time coming!

Before we start I should point out a couple of things. Firstly I have moved on to a newer version of Unity (V2017.2.0f3) and also a new version of PUN (V1.87), and you may encounter some errors if you are still using an older version of Unity, so I would recommend you upgrade your Unity version to match before following this tutorial.

Secondly, I am changing the format of the tutorial slightly, and as such I will now provide the full project for you to download at the beginning of each part of the tutorial; I will then go on to provide explanations of all the new script changes and additions.

The reasoning behind this is that as the tutorial progresses, the game setup will become more complex and I will end up spending more time describing how to add and make changes to the game scene, HUD, game objects etc. than describing how the networking code works, and as this is above all a networking tutorial I didn’t think that was an ideal scenario.

You can download the project files for this part here.
(To run the game in the editor, load Assets/Main Scene and press play.)

You can download the project .exe here.

New scripts added in this part 5.

PlayerShoot.cs
PlayerScore.cs
PlayerHealth.cs
Missile.cs

Part 5a – Player Shooting
The first thing we want to do is give our players the ability to fire their guns and to achieve this I have added a new script to our player prefab called PlayerShoot.cs.

You’ll notice that the PlayerShoot script is a PunBehaviour rather than a mono behaviour. We can do this because it is a component of a GameObject that has a PhotonView component, and by making the PlayerShoot script a PunBehaviour it automatically gets access to the cached photonView and all the Photon events and callbacks.

The PlayerShoot script starts off by setting up a reference to the missile prefab (set in the inspector) and setting a couple of variable values that will be used to control the rate of fire.

We only want this script to run on the PC of the local player, and the easiest way to achieve this is to disable it on all clients where photonView.isMine is false, which we can do in the Awake function as follows.

In the Update function, we check the fire timeout and fire button state to see if we should launch a missile and if both the timeout is up and the fire button is pressed, we can launch one using an RPC call, which I will explain below.

I decided not to give the missile a PhotonView and instead have it as a non-networked object as this will save on network traffic; however, that does mean we can’t use PhotonInstantiate to create a copy of it on every client at once. So if we implemented the missile launch as a normal function, it would only fire a missile on the local client and other players in the game wouldn’t see it.

To overcome this we will give the missile launch function the PunRPC attribute, which marks it as a Remote Procedure Call (RPC), which we invoke with the PhotoView.RPC() method. Essentially what this does is cause the invoked function to run on one or more remote clients as well as our own (depending on the arguments supplied) and we can use this to launch the missile on all clients.

The PhotonView.RPC function takes a minimum of two arguments, the first being the string name of the function we want to invoke and the second is a target player or an enumeration that determines which clients should run the function. In this instance, we give it the name of our missile launch function “RPC_FireMissile” and PhotonTargets.All for the second argument. This means that the function will run on all clients including the player that fired the missile on the GameObject with the corresponding photonView.

RPCs can also take additional parameters, and I will cover that later in the tutorial.

This is the missile launch function. I give all my RPC functions the RPC_ prefix, however, this is a personal preference and isn’t required.

You’ll notice that although we didn’t pass any parameters to the RPC, it has actually got one parameter (PhotonMessageInfo info), this is automatically available for all RPCs and contains a couple of often useful bits of information. In this instance, we will use it to obtain the photonView of the player that fired the missile. (the PhotonMessageInfo parameter can be omitted if you don’t need any of the information it provides).

So the first thing the fire missile script does is instantiate a new missile with the position and rotation of the player object (which this script is attached to) and cache a reference to it. Then it passes the photonView of the player that fired the missile to the missile script so we can know who owns this missile. This will allow us to easily identify who should get a score increase if the missile hits another player. Lastly, it sets the missile GameObject active.

As far as the PlayerShoot script is concerned that’s it for the missile, movement and collisions are handled elsewhere; so it can relax until the next time the fire button is pressed.

Part 5b – PlayerHealth and PlayerScore
Before we move onto the missile let’s take a look at the PlayerScore and PlayerHealth scripts as they will be referenced by the Missile script. For now, both these scripts are quite basic and do little more than output debug.log  text. They will both be expanded upon in the next part of the tutorial series.

This is the PlayerScore script, which is attached to the Player prefab.

This simple script contains a variable for storing the current score and an RPC function for adding points to the score and logging the new value to the debug console.

This is the PlayerHealth script, which is attached to the Player prefab.

This simple script contains a constant and variable relating to max health and current health. It also has a function for applying damage (reducing hitPoints) based on the damage of the missile passed to the function and a function to display in the debug console, the health as a percentage of the maximum HP.

Part 5c – The Missile
So let’s now take a look at the missile.

The missile itself is just a red sphere with a rigidbody and a couple of child particle systems for the trail and explosion. The missile prefab is contained in the Player folder.

The missile script contains references to the rigidbody and particles systems (set in the inspector) and missileOwner, speed and damage variables.

As soon as it is enabled, the missile simply uses FixedUpdate to move forward by
speed * Time.fixedDeltaTime every physics update. As this script runs on every client all players will see the missile moving, even though it isn’t networked. This is workable because the missile trajectory is straight and the missile is relatively short-lived, so there isn’t much opportunity for the missiles to become out of synch with different clients.

Next, we have the SetOwner function, which we called from the PlayerShoot script, this simply caches the passed PhotonView for use later by the collision function.

Now comes the OnTriggerEnter function, which is where we will deal with collisions.

Firstly we check to see if we hit a player. If we did then cache a reference to the attached PlayerHealth script on the player that was hit.

We only want one client to take action in the event of a hit and in this case, we will have the player that is hit be responsible for dealing with it. So we put in a condition that checks hitPlayer.photonView, and if isMine is true then this script is running on the client that was hit.

Next, we want to ignore collisions between our own missile and our own tank (unlikely, but could possibly happen just after being fired), which we can easily do by comparing the hitPlayer’s photonView.viewID with the same as the local player photoView.viewID. If they match we just return from the function.

If we get this far it means we have registered that we have been hit by someone else’s missile, so we call the DoDamage() function on our own PlayerHealth script.

We also need to tell the player that hit us to increase their score, and as this needs to be executed on a remote client we need to make use of the RPC function again, but using a different set of arguments to when we used an RPC in the PlayerShoot script.

The first argument is the name of the RPC_AddScore function in the PlayerScore script.
For the second argument, we use missileOwner.photonView.owner to supply the PhotonPlayer object of the missile owner. This means that the RPC will only be executed on the client of the player that fired the missile; Which in turn means that scores will only be tracked by the local player, which I have done purely to demonstrate a second way to use an RPC. (Later in the series, this will be changed to allow everyone to see all players’ scores.)

Lastly, as the RPC_AddScore function takes an argument for the score, we add 25 as the last parameter to the RPC function, as this will be the amount we want to add to the score each time we score a hit.

That’s all we need to do in the event a player was hit, which only leaves one more thing to do in this function and that is to destroy the missile regardless of what it hit. The last line of the function does this by calling the DestroyMissile function. As this function is called outside of the photonView check above, it will be run for all clients, which is what we want, because all players should see the missile explode.

This function Destroys the missile GameObject. But to allow the explosion particle to play and the trail particle to slowly fade out they are both unparented from the missile first. Then the trail particle is set to stop emitting and the explosion is played. Both particles have been set in the inspector to automatically destroy when they have finished.

Now when you play the game you should be able to fire missiles and when you get hit (if playing in the editor) you will get a Debug.Log of your HP percent and when you hit someone else you will see a Debug.Log of your points score.

That’s it for this part of the tutorial series, in the next part we will expand the health and score system and provide better visuals for them.

Hope to see you then.

You can download the project files for this part here.
(To run the game in the editor, load Assets/Main Scene and press play.)

You can download the project .exe here.

Photon Unity Networking Game Tutorial Part 4 – OnConnectedToMaster and Spawn Points

Welcome to part 4 of my Photon Unity Networked Game tutorial. In this part we will create a system for easily adding spawn points to any level, and also makes some improvements to the main menu.

Part 4a – Menu Changes
If you’ve been following the tutorial up until now, you may have noticed a minor bug when clicking the join game button. If you click it very quickly after starting the game you can get a run time error ‘JoinOrCreateRoom failed. Client is not on Master Server or not yet ready to call operations. Wait for callback: OnJoinedLobby or OnConnectedToMaster.’

This is because it takes a few seconds for the Photon networking system to connect and be ready, and until this is the case you can’t start or join a game. So to avoid the possibility of this happening we’ll disable the join game button until Photon tells us it is ready. While we are at it we’ll also make some changes to the way we have organised the menu in the game scene, in preparation for features that we’ll be adding later in the tutorial.

First of all rename the MainMenu game object to HUD and then change the Canvas Scaler UI Scale Mode to Scale With Screen Size. Next, add an empty game object as a child of HUD and call it MainMenu, then add an empty game object as a child of MainMenu and name it UI. Then make the JoinGameButton a child of UI by dragging it onto the UI game object in the hierarchy.

This is how your Hierarchy should look once all that is done:-

Now we need to write a small script for the MainMenu game object to handle the state of the join game button and the visibility of the main menu, but before we do that we need to add an extension class that we’ll use to find game objects by name, even if they are disabled. So create a new folder in Assets and call it Extensions, and in the extensions folder create a new c# script and call it TransformExtensions.
Then open the TransformExtensions script in your editor and replace the default code with this:-

This will add a new method to instances of transform (transform.FindAnyChild()) that will make it easy to get references to our HUD items without having to drag them into exposed properties in the inspector. Before you move on save the TransformExtensions script.

Now we can get to work on the HUD and MainMenu scripts, so create a new folder in Assets and call it HUD, and in the newly created  HUD folder create a c# script and call it HUD.
We will implement HUD as a singleton and use the DontDestroyOnLoad method to make it persist between scene changes in the same way we did with the GameManager script.

So open up the HUD script and replace the default code with the following and then save it :-

Now add the HUD script to the HUD game object by dragging the script onto the HUD game object in the hierarchy window.

For the time being that’s all we’ll be doing with the HUD, its main purpose is to act as a holder for all the game UI elements, however I may add some extra functionality to it further into the tutorial series.

Next, create a new c# script in the Assets\HUD folder and call it MainMenu, then add it to the MainMenu game object in the hierarchy by dragging the script onto it. Once again this is going to be a singleton, so open the MainMenu script for editing and replace the default code with this :-

You may have noticed that as well as making this a singleton class, it has also been made to inherit from Photon.Punbehaviour, this is so that we can override one of the Photon methods later in the script.

So next we need to start adding some code to allow the MainMenu script to enable the join game button when it’s okay to do so.

So firstly add these two lines to the top of the MainMenu class:-

And then add the following lines to the bottom of the Awake() function:-

What this does is find the UI game object and JoinGameButton in the menu hierarchy and stores the references in the two variables we declared, for easy access later. It then enables the UI game object (in case it has been disabled in the editor), which in turn means the join game button is visible, and then it makes the join game button non-interactable, so we can’t join a game until Photon is ready for us.

Having the menu (and later on, other UI elements) hierarchy organised in this way mean we can easily hide UI elements in the inspector (which can help to keep the scene view less cluttered with UI stuff), without disabling their associated script, which means that we don’t have to worry about their initial state when the game runs, and they will activate/deactivate themselves as required.

Save the MainMenu script and run the game, you should see that the join game button isn’t clickable, and you can’t proceed past the main menu.

All we need to do to fix this is add the following method :-

This method is called on all Photon.Punbehaviours once the game is connected to the Photon master server and is ready to host or join a game. By overriding it we can take whatever action we want at that point, and in our case we just make the join game button interactable.

We just need the MainMenu script to do one more thing for now, and that is disable or enable itself depending on whether we are in a game or not, we can do this by using the value of PhotonNetwork.inRoom in the Unity OnLevelwasLoaded() method. So add the following method below the OnConnectedToMaster() method:-

When a level is loaded this will hide the Main Menu if PhotonNetwork.inRoom is true, and show the Main Menu if it’s false;

This is the complete MainMenu script as it currently stands :-

If you save the script and run the game, you should notice the join game button starts disabled, but becomes enabled after a few seconds, at which point you can use it to join a game.

Before moving onto the next part make sure to save the scene now if you haven’t already done so.

Part 4b – Spawn Points
As it currently stands all players spawn at the same fixed part of the map, which obviously is far from ideal, so now we’ll put in place a flexible method of adding spawn points to the game level.

The first thing we need to do is create a SpawnPoint class, so create a new folder in Assets\Player and call it SpawnPoints, and in that folder create a new c# script and name it SpawnPoint. Open the SpawnPoint script for editing and replace the default code with the following, and save the script :-

As you can see it’s very simple, and the only thing it actually does is disable the game object it’s attached to as soon as it runs. We don’t actually need it to do anything else, except provide us with position and rotation information, which we can get from its transform component. To make any object in the scene a spawn point you can just add this script to it.

Now we need to add some spawn points to our game level, so open the Game Scene (save the current scene if prompted), select the CompleteLevelArt game object and add an empty child game object (GameObject->Create Empty Child). Rename the empty game object SpawnPoint and then add the SpawnPoint script to it by dragging it onto the SpawnPoint game object in the hierarchy window.

To make it easier to locate in the Scene view, give the SpawnPoint game object an icon, by clicking the coloured cube in the top left hand corner of the inspector window and selecting the green bar icon.

This is how it should look at this point :-
SpawnPoint

Now change the transform settings for the SpawnPoint as so:-
spTransform1

Then make a duplicate of the SpawnPoint (CTRL + d) and change its transform settings as so:-
spTransform2

Then make a further duplicate of the SpawnPoint and change its transform settings as so:-
spTransform3

Obviously these placings are just examples and you are free to create as many spawn points as you like and place them however you want. But assuming you followed my example then the game scene should look like this now :-
GameScene

Go ahead and save the Game Scene, and we’ll move on to making it so that the player can randomly pick one of the spawn points when the level is loaded.

The next thing we need to do in order for that to happen is to make some changes to the GameManager script (Assets\GameManager\GameManager.cs). So open it for editing and add the following using statement to the top of the script:-

Next add this static helper method to the bottom of the GameManager script:-

This performs a similar function to the Unity function GameObject.FindObjectsOfType(), but unlike that function it will also find inactive objects. The reason we need it be able to do that, is that we can’t be certain that the SpawnPoints won’t have deactivated themselves by the time we come to search for them.

Next, add this function above the GetAllObjectsOfTypeInScene function :-

This will return the transform component of one of the spawnpoints that it finds in the scene or the default spawn point (we’ll get around to that next) if it doesn’t find any.

To implement the default spawn point we need to add this member variable to the top of the script:-

And we initialise it during the awake function with this code, which just creates a new game object and gives its transform some default values.

The final part of the this particular jigsaw is to give the spawn point position and rotation to the player when it is instantiated. And to do this we need to make a couple of changes to the OnLevelWasLoaded() method.

We add the following line after the PhotonNetwork.inRoom check:-

and then change the statement that instantiates the player, so that it can use the spawn point information, as so:-

This is the full GameManager script with all the above changes in place:-

Save the GameManager script, open the Main Scene (save the current scene if prompted) and run the game, and you should see that the player now spawns at one of the points you placed in the game scene earlier.

So that’s it for this part, we’ve now got a less buggy main menu (the main menu will be completely reworked later in the series) and we have a simple and flexible method for adding spawn points for our players. In the next part we’ll be adding some weaponry.

As always any questions, comments and suggestions are very welcome, see you soon.

Download complete project for Part 4

Photon Unity Networking Game Tutorial Part 3 – Adding the Player and Game Scene

Welcome to part 3 of my Photon Unity Networked Game tutorial. In this part we will add the player object and the game scene.

Disclaimer: There are many solutions to any one given network game design, which will differ greatly due to a number of factors, including but not limited to, target audience numbers, security concerns and whether you are programming for fun or commercial gain.
Therefore, I do not suggest that is this the only approach you might take, or that this is even the best one, rather it is my attempt to demonstrate some core concepts in as clear and concise a fashion as possible, which can be used as a stepping stone into the often murky waters of networked game programming.

Part 3a – Setting up the game scene
Before we can set up the game scene in the editor we need some assets for the environment. This zip file contains a Unity package which has in it the game scene and player prefabs which are modified versions of some of the excellent assets from the Tanks Tutorial from the Unity Asset Store. Go ahead and download it then extract and install the Unity package.
After you’ve installed it your project folders should look like this (I have highlighted the new folders contained in the package).

ProjectWindow

Now that we’ve got the assets installed, make a new scene (File->New Scene).

Delete the default directional light (the level art prefab has its own lights) and then find the level art prefab (UnityTanksAssets\Complete\Prefabs\CompleteLevelArt.prefab) and drag it into the Hierarchy Window, and make sure the transform position is 0,0,0.

DragLevelArt2

You should now have a nice gaming arena in the scene, however the lighting is a bit ‘flat’ by default, so the next thing we need to do is adjust that. Open the lighting window (Window->Lighting) and set the following values:-

Skybox = Default-Skybox
Sun = None (light)
Ambient Source = Color (Set the Ambient Color RGB values to 133, 102, 0 to get a mid brown colour)
Precomputed Realtime GI = Ticked
Baked GI = Un-ticked
Auto Build = Un-ticked

This is how the lighting window should look

LightingSettings

This is how your editor should look if you have correctly imported the assets and added the level art to the scene.

Save the scene in the Assets folder, and call it Game Scene. Next we’ll add some code to handle loading of the game scene when we join a game.

Part 3b – Loading the game scene
Once you have saved the game scene you need to add both the Main Scene and the Game Scene to the scenes in build, so open the build settings window (File->Build Settings) and drag them both into it as so, making sure that the Main Scene is first in the list.

BuildScenes2

Next, open the GameManager script (Assets\GameManager\GameManager.cs) for editing.

All we need to do is add this snippet of code to the OnJoinedRoom() function

and this line of code to the end of the Awake() function

What this does is, if you are the host (first player in the game) it instructs the Photon Networking system to load the game scene level. And then the line we added to Awake() ensures that any new players joining will automatically load whichever scene the host has currently loaded.

Strictly speaking as we are only using the one game scene at the moment, we could make the host and clients load the game scene manually using Unity’s SceneManagement class, however if we come to add extra game arenas later, doing it this way will make it much easier to keep everyone synchronised. If the host changes its current scene, then all connected clients will automatically change to the same scene, and new clients will join with the same scene active.

Note: Photon uses the term MasterClient to indicate which client is currently the host and ‘in control’. The Master Client can be used as “authoritative” client/player to make decisions, run AI or carry out other tasks that you don’t want all clients to be able to do themselves. If the current Master Client leaves the game, Photon will very quickly assign someone else, which means that the game doesn’t stop if the host leaves.

This is the full GameManager script with the additions we just made, so go ahead and save this now, and then open the Main Scene again in the editor.

If you build and run two instances of the game, you will see that once you click the join button, the scene switches to the game scene. This happens on the client as well, even though we don’t explicitly load the scene on the client, because we set PhotonNetwork.automaticallySyncScene = true.

If you run one of the instances in the editor, and you don’t see the main menu when it runs, that is because you didn’t switch back to the Main Menu scene after you had finished making the Game Scene.

So that’s the game scene working, next we’ll add the player.

Part 3c – The Player
Before we can add the player object, we need to make a couple more changes to the GameManager script as follows:-

First we need to declare a variable to store a reference to the local player object when it is instantiated as so:-

public static GameObject localPlayer;

We can use this as a handy way to reference the player object any time we need to.

Then we need to add the following function:-

The above function will run whenever a scene loads, including the main menu. So to avoid spawning the player when we aren’t in the game scene we check to see if we are in a room or not. The game scene won’t load until we have joined a room, so if we are in a room we know that we must be in the game scene, and therefore we need to instantiate the player object and we also store a reference to it in the variable we just added. Otherwise we just return.

This is the full GameManager script now, which you can now save before proceeding:-

We imported a player object along with the level art, but we need to get it ready for networking before we can use it in our game, so navigate to the Assets\UnityTanksAssets\Complete\Prefabs folder and select the Player prefab located in there.

With the player prefab selected, click the Add Component button in the inspector, type photon in the search panel and add a Photon Transform View from the list of components.

TransformView

This will add a PhotonTransformView and a PhotonView component to the player prefab, and it is these components that will do the work of synchronizing our player object across the network.

We need to tell the PhotonTransformView what we would like to synchronize, and in our case that will be position and rotation, which we indicate by ticking the two relevant boxes. When we tick each box further options will appear relating to ‘smoothing’ of the networked player movement on remote clients. We’ll leave these values on their defaults for now.

Lastly we drag the PhotonTransformView component into the Observed field of the PhotonView component. The PhotonView will then be able to send the position and rotation of our player object across the network.

TransformView2

The Photon instantiate command requires that the prefab is contained within a Resources folder, so we’ll sort that now. Create a new folder in Assets and call it Player, then in the Player folder create another folder and call it Resources. Next, drag the Player prefab from the Assets\UnityTanksAssets\Complete\Prefabs folder and into the Assets\Player\Resources folder.

Next create a new script in the Assets\Player folder and call it Player and then open it for editing.

Replace the default code with the following:-

This does three things, firstly it makes sure that the player object is set to DontDestroyOnLoad, so that if we change levels during the game our player won’t get destroyed.
Secondly, it grabs a reference to the Camera gameobject attached to the Player prefab.
Thirdly it checks to see if photonView.isMine is false and if it is, it disables the player camera.

photonView.isMine is how we determine if this script is running on the local player object (the one we are controlling) or on a player object belonging to a remote player. True means that it is our Player object, false means it belongs to someone else. We only want the camera to be enabled for our own player object.

Note that this script derives from PUNBehaviour, which gives us easy access to lots of Photon stuff. In this case it gives us convenient access to the attached PhotonView component via the photonView property.

Save the script and then add it to the Player prefab (select the player prefab, click the Add Component button in the inspector and select Scripts->PunTutorial->Player).

You can now build and run two instances of the game, you’ll see that when the 2nd player joins it spawns in the same place as the first player, and the physics moves them apart. You’ll also notice that the positions of the tanks is synchronised in both clients, which means the PhotonTransformView component is doing its job.

Now we need to add a script to allow us to drive the tanks.

Create another new script in the Assets\Player folder and call it PlayerMovement and then open it for editing.

Replace the default code with the following:-

Notice that it derives from Photon.PunBehaviour, so we can easily check photonView.isMine. If it’s false, we disable the script as we only want this to run on our local player object.

I won’t go into much detail about how the rest of this script works, as it isn’t particularly relevant to networking. But basically it reads the values of the horizontal and vertical input axis, and uses those values to move and rotate the rigidbody of the player object.

Save the script and then add it to the Player prefab (select the player prefab, click the Add Component button in the inspector and select Scripts->PunTutorial->PlayerMovement).

There’s just one last thing we need to do, and that’s to remove the camera from the game scene, as our player prefab has its own camera attached and we’ll use that instead. So open the game scene, delete the Main Camera game object, then save the scene.

Next, open the Main Scene again, and if you run the game you’ll see that you can control the tank with the WASD keys. If you build and run two instances of the game, you’ll see that each tank can be controlled independently, and that their movement is synchronised across both clients.

That’s it for this part of the tutorial, in the next part we’ll add a system to handle different spawn positions.

See you next time.

Download UnityTanksAssets package
Download Complete Project for Part 3

Scene Transition/Screen Fader Tutorial Part 2

Welcome to part two of my screen fader tutorial. In this part I will provide a short demonstration of how you might use the screen fader to smoothly transition between scenes.

I’ll add two scenes to the project, with different title text and background colour, so it’s obvious when the scene has changed, and a single button in the middle of the screen which will be used to make the scene change.

I’ve added a small script to the button, which exposes an Object property to the editor, into which I drag the scene that I would like the button to load when clicked. Note: any scenes that are to be loaded at runtime must be added to the build settings in the editor.
Build Settings

This button script is how an inexperienced Unity programmer might approach it, but it won’t work properly and if you try it you’ll see that the scene change happens immediately with no fade in or out.

The reason for that is that as soon as the fade out function is called Unity moves immediately onto the next line of code and executes it, this stops the fade out and loads the next scene. It then goes on to start the fade in function, which has no effect as the screen isn’t faded out.

So how do we prevent execution of the line after the fade out call until we are ready for it? One way would be with coroutines, but this can easily get messy and means that we can’t keep all our code in one function. So this is where the callback argument of the fadein/fadeout functions comes into play.

With the above in mind we could write our button code like this instead:-

So now we have separated the fadeout function call from the load scene and fadein function calls, and put them in a separate function. We have then provided the new function as the callback argument for the fadeout routine.

Now if you run the program and click the button you’ll see that it works exactly as it should, the original screen fades out, and then the new scene smoothly fades into view.
This is because now the fadeout routine is executing and only when it’s finished does it invoke the callback function which loads the new scene and fades it back in.

This is much better, in as much as it actually works. However earlier I mentioned that a disadvantage of using coroutines to achieve the same was that we couldn’t contain everything in one function, and you’ll probably have noticed by now that this solution suffers from the same problem.

We can fix that however by writing the callback function inline in the fadout function call, this isn’t strictly speaking necessary, but in a lot of instances it can keep the code simpler and easier to follow in my opinion.

So this is the final version of the button script:-

As you can see the whole process is now contained within a single 7 line script, with execution of the scene change and fadein delayed until the fadeout function has finished. I’ve also added a 0.5f second delay to the fadein function call as I think it looks better with a slight extra delay.

That’s it for this tutorial, as always any and all comments or suggestions are welcome. See you next time.

Unity project file

Scene Transition/Screen Fader Tutorial Part1

A common feature of games is that the screen briefly fades to black during scene changes. This is done to ‘soften’ the transition as a sudden switch from one scene to another can be a bit jarring if it’s visible when it happens.

So I’ve found it handy to have a screen fader that I can easily drop in to a new project any time I want to have fade to black (or some other colour) scene transitions and I decided that it would be a nice subject for a mini tutorial. It will also serve to demonstrate a couple of seemingly often overlooked but very useful features, i.e. callbacks and CanvasGroups.

The aim of this tutorial will be to provide a screen fader that is fairly simple to implement and is also flexible and easy to use.

The way this screen fader will work is by overlaying a UI image on the screen and changing it’s alpha value to fade it in and out.

To make it as easy as possible to add to a project, we’ll have the fader create its own UI elements in code, which means all we have to do is drop the screen fader script onto an empty game objet to make it available for us to use. To make this work we’ll need the screen fader to create its own Canvas, CanvasGroup component and an Image.

Step 1)
This is the code to create the Canvas at runtime:-

What this does is create a new GameObject with a Canvas component attached. It then parents it to the GameObject that script is on, then it sets the RenderMode to ScreenSpace overlay and sets the sort order to the value specified in the inspector (default 99). I have made the sort order easy to change so that you can make sure the fader image is always on top of everything else. However depending on what you wanted you could also use the sort order to have it appear behind some elements.)

Step 2)
This is the code to create the CanvasGroup at runtime:-

We use AddComponent() to add the CanvasGroup component to the canvas we just created, and then store, in a member variable, the reference to the component that it returns for later use. Then we set interactable and blocksraycasts to false, which means that any child objects of the canvas group won’t block mouse clicks. This isn’t strictly necessary for our purposes here, and indeed in some instances you may want your screen fader to block input, in which case you would set interactable and blocksraycasts to true.
Lastly we disable the GameObject as we don’t need to have it enabled until we are ready to use it.

Step 3)
This is the code to create the Image at runtime:-

Firstly we create a new GameObject with an Image Component attached, then we set it as a child of the canvas we created in step 1. Next we set its colour to the value specified in the inspector (default black), and lastly scale it up a bit, this last bit is done to prevent a slight border appearing around the edges in some screen resolutions.

Step 4)
Set the image position and size and make it scale with the screen size:-

The easiest way to change position and size of ScreenSpace UI elements is to use the RectTransform component, so firstly we get a reference to the Image RectTransform using GetComponent().

Next we set the anchors to the bottom left and top right to make the image stretch with the screen size. The anchors are Vector2s with values between 0,0 and 1,1, where 0,0 is the bottom left of the screen and 1,1 is the top right of the screen.
Next we centre the image by setting its anchoredPosition to 0,0;
Lastly we set the width and height to match the current screen size (due to the scaling we did in step 3, it will be slightly larger than the screen).

Now we need to put all of that above into the Awake function of the screen saver. This is the complete Awake() function.

The only part of the Awake() function I haven’t discussed yet is the very first block of code. Basically what this does is make the screen fader not get destroyed during scene changes, and also ensures that the only instance of it that can exist is the first one that is created. It also grabs a static reference to the first instance so that it is possible to access non static methods and properties.

That’s the basic setup finished, so next we’ll define a couple of static methods that will enable us to perform fade outs and fade ins. The methods will invoke callbacks when finished so that we can delay execution of other code whilst the fader is in operation. We will also be able to specify a delay before and/or after the screen fade.

This is the public static method to do a fade out:-

As you can see it is quite simple, all it does is check to see if the callback argument is null, and if so it points it to the default empty callback function and then it sets the canvas active.
Next it stops any current fade in/out operations (I’ll discuss that function further on) and runs the fade out coroutine, which is where most of the work is done.
It uses the variant of StartCoroutine that returns a CoRoutine object, which we store for use by the StopActiveFades() function.

This is the code for the fade out coroutine:-

There again, this is quite straightforward, first of all we yield wait for the delayBefore period.
Then we loop while the group.alpha property is less then 1. The alpha property controls the transparency of all children of the group (in this instance our image we created in step 3), a value of zero means fully transparent and a value of one means fully opaque.

In the while loop we use MathF.MoveTowards to linearly fade from transparent to opaque, we can use the speed property in the inspector to control how quickly this happens.
After the while loop exits we yield wait for the delayAfter period if any, and then we invoke the callback to signal that the fade is done.

The fade in functions are almost identical, except in the while loop we change the group.alpha from one to zero and when it’s finished it disables the canvas.

Now let’s take a look at the StopActiveFades() function:-

This function just ensures that there can’t be two fade operations running at the same time, as that could result in unwanted behaviour.
What it does is check the fadeInCR and fadeOutCR variables and if they aren’t null it stops the coroutine they point to and sets the variable to null.

Last of all is the default empty callback function, which doesn’t need any explanation.

In the next part of this tutorial I will show how we can use the screen fader in our applications, but in the meantime here is the full screen fader script:-

As always any and all comments are welcome, see you next time.

Arcade Style Bouncy Vehicle Physics Tutorial

What is this tutorial?
In this tutorial we will look at how to set up arcade style vehicle physics on a 3D model. As with my previous tutorial, in an attempt to keep it as clear and concise as possible I will keep the game design quite simple, therefore this should be seen as a basis from which to build a game, rather than a tutorial for a complete and finished game.

Who is this tutorial aimed at?
This is aimed at people with a reasonable knowledge of C# and Unity as I won’t be explaining in depth basic C# programming concepts or basic Unity concepts, unless it is appropriate to do so within the scope of the tutorial.

Part 1 – The vehicle game object

 As this is a tutorial on coding rather than building game objects in the editor, I’m not going to give step by step instructions on how to put together the car and terrain, instead I’ll just give a brief description of the important bits and how they relate to the code, and I’ll provide all assets in a download link at the end of the tutorial.

First of all I should point out that the method we will be using isn’t a realistic physics simulation, instead it uses forces to ‘fake’ the physics, but the outcome is reasonable and gives a nice Mario Kart style feel to the vehicle handling.

The way we’ll achieve this is by firing a raycast down from each corner of  the vehicle a certain distance (hoverheight), and if it detects a hit, it adds an upward force. We also adjust the strength of the upward force depending on the distance from the vehicle that the raycast detects the hit. So effectively the closer the vehicle gets to the ground the stronger it is pushed back away from it, and vice versa.

The length of the ray we fire can be adjusted, and the longer it is the further the vehicle will float above the ground, we will be using a fairly short ray, because we want this to appear as if it is actually on the ground. However by increasing the hoverheight and hoverforce you can simulate a nice hover car type behaviour instead.

This is a very basic example of how we would set up the vehicle game object with the hover points. The red circles indicate where the hover points are positioned. Notice that they are placed vertically above the centre of the vehicle, this is because of the way we simulate gravity in our code, as I’ll explain a bit further on.

HoverCarBasic

We’ll also attach a rigidbody component, and for this example we’ll give it a mass of 70, drag 3 and angular drag 4. These figures work quite well as they are, but you can achieve different handling effects by tweaking them also.
Lastly we give it a box collider to detect collisions with other scene objects and also to prevent the vehicle from falling through the terrain when the downward velocity is very high and we’ll put it on its own layer (vehicle), so we can ignore it in the raycasts.
We’ll also untick Use Gravity, as we will be handling gravity ourselves.

So that’s pretty much all that’s needed for a basic vehicle setup (in the finished project I have added a buggy model which looks a bit nicer than a plain cube).

Part 2 – The code

So now let’s take a look at the code that will turn this into something a bit more interesting. First off we’ll add the various properties that we’ll use to control the behaviour of the buggy as so.


Most of this should be pretty self explanatory, but I’ll explain what some of them do.

The deadZone value is just a way to make the controller not so sensitive to small movements. Basically any input below the deadZone threshold is ignored.

The groundedDrag value is used to change the buggy RigidBody drag factor depending on whether the buggy is grounded or in the air.

The dustTrails array will hold references to the particle systems that play when the wheels are grounded.

The layerMask property is used to prevent the hover point raycasts from registering hits on the buggy.

Next we have the Start function, which stores a reference to the buggy Rigidbody and stores a reference to the inverse of its LayerMask, for use in the Raycast later.
It also sets the Rigidbody.centerOfMass to be one unit below the buggy, this helps to keep it a bit more stable when it’s in the air.

In the Update function we read the current input and assign a value to the acceleration and rotation from it.

Most of the work is done in FixedUpdate, so let’s take a look at this one bit at a time:-

This block of code above handles the hover/bounce behaviour.
To start with it clears the grounded flag.
Then, for each of the hover points, it fires a raycast of hoverHeight length downwards, and if it detects a hit it applies a force in the opposite direction and scales it depending on the distance the hover point is away from the hit point. So the closer the hover point is to the point which the ray cast hits, the greater the force that is applied to push it back. Kind of like what happens when you compress a spring.
Grounded is also set to true if any of the raycasts detect a hit.

If, however the hover point raycast doesn’t detect a hit, then that means this wheel/corner of the vehicle is off the ground, so we need to handle this differently as follows.

It compares the y position of each hover point with the y position of the vehicle, and pushes it up if it’s below it, or down if it’s above it. This serves two purposes, firstly it makes the vehicle automatically level out when it’s in the air, and secondly it applies a fake gravity effect. This is why the hover points need to be positioned above the centre of the vehicle transform, so that when the vehicle is in the air it will be pushed back down by the gravityForce amount. If we positioned the hover points below the y position of the vehicle transform, once it left the ground it would fly up into the air and never come down.

The next section of code handles other behaviour differences between when the vehicle is grounded and when it is airborne.

So basically, if the vehicle is on the ground, we set the Rigidbody.drag value to the amount we set in the inspector, and we give the dust trail particles a suitable emission rate.
But if the vehicle is in the air we set the Rigidbody.drag to a very low value, and we also drastically reduce the thrust and turn values, as we don’t want to have full control whilst we aren’t on the ground.
Lastly for this section, we iterate through the dustTrails array and set the particle emissionRate to the appropriate value (10 if grounded, zero if in the air).

Last of all we apply the thrust and turn forces to the vehicle and then limit it’s velocity to the maxVelocity value we set in the inspector.

So that’s the entire vehicle controller script, it produces quite a nice arcade style drive and with a bit more work could form the basis of a fun driving game, you can test out the complete project which can be downloaded from here. Once you have loaded it into Unity you will need to open Assets\Scene 1.

The behaviour of the vehicle can be modified to make it feel like it’s driving on different surfaces by changing the various properties exposed in the inspector, for example to make it feel like it’s on ice change the following properties:-

  • Grounded Drag = 0.5
  • Max Velocity = 30
  • Forward Acceleration = 1500
  • Reverse Acceleration = 750
  • Turn Strength = 500

It uses the standard WASD and Arrow keys to control acceleration, braking and turning.

Thanks to Carbon Concept for the free buggy model

I hope you enjoyed this tutorial, and please feel free to post any comments or suggestions.

Download project files