uLink tutorial 1 - Developer

54 downloads 364 Views 363KB Size Report
The goal of this tutorial is to show some basic features of the uLink ... short tutorial starts from a clean Unity project and explores the basic concepts of uLink.
uLink tutorial 1

1 Introduction The goal of this tutorial is to show some basic features of the uLink networking library for Unity. This short tutorial starts from a clean Unity project and explores the basic concepts of uLink. It explains how to start a server, how to start and connect a client to it, and how to instantiate one network-aware object. The final exercise is to write and execute a remote procedure call. All code samples are written in C#. Extra information that is not essential to the tutorial, but that is still noteworthy, is written in a box like this one.

2

Installing the uLink library

Getting uLink up and running is very easy. The library can be downloaded and installed in a few simple steps. 1. Download the latest version of uLink from http://www.unitypark3d.com/download, and run the installer. 2. During the installation, you can choose to install additional components if you'd like, but the uLink component is all that you need for this tutorial. 3. Once the installation is complete you can begin using uLink right out of the box! If you want to update the uLink library, all you have to do is run the latest installer to overwrite the old version. Just remember to re-import it in your Unity projects using uLink after you've updated it.

3 Importing the uLink library To be able use uLink in a Unity project, you have to import the library first. This is illustrated below. 1. Start Unity, then create a new project and name it "uLink Tutorial 1". Check the uLink package in the include list.

1

2. Create the project and verify that the uLink folder is visible in the Plugins folder, in the Project View. If you forget to check the uLink box when you create a new project or just want to import it into an already started project you can do this by selecting Assets >> Import package... from the Unity menu. The package is located in a subfolder to the Unity program folder which is named Standard Packages. The path can look something like this: C:/Program Files (x86)/Unity/Editor/Standard Packages. uLink has been developed for Unity 3.x and 2.6.x.

4

Starting a server

The next step is to write some code that will start a game server. 1. Create a new folder called "Scripts", by Assets >> Create >> Folder. 2. Create a new script by Assets >> Create >> C Sharp Script. Rename it to "ConnectionGUI". 3. Drag it to the Script folder if it is not already located there. The picture below shows the result

2

so far.

4. Open your new script in an editor by double-clicking it. Replace the sample code in the script with the following. Note that all sample code is also included in the Scripts folder that came together with this tutorial. using UnityEngine; public class ConnectionGUI : MonoBehaviour { public string serverIP = "127.0.0.1"; public int serverPort = 7100; void OnGUI () { // Checking if you are connected to the server or not if (uLink.Network.peerType == uLink.NetworkPeerType.Disconnected) { // Show fields to insert ip address and port serverIP = GUI.TextField(new Rect(120,10,100,20),serverIP); serverPort = int.Parse(GUI.TextField(new Rect(230,10,40,20),serverPort.ToString())); if (GUI.Button (new Rect(10,10,100,30),"Connect")) { //This code is run on the client uLink.Network.Connect(serverIP, serverPort); Debug.Log("Did send call to server"); } if (GUI.Button (new Rect(10,50,100,30),"Start Server")) { //This code is run on the server uLink.Network.InitializeServer(32, serverPort); } } else { //This code is run when a connection is established string ipaddress = uLink.Network.player.ipAddress; string port = uLink.Network.player.port.ToString(); GUI.Label(new Rect(140,20,250,40),"IP Adress: "+ipaddress+":"+port); if (uLink.Network.isServer) GUI.Label(new Rect(140,60,350,40),"Running as a server"); else if (uLink.Network.isClient) GUI.Label(new Rect(140,60,350,40),"Running as a client");

3

} }

void uLink_OnServerInitialized() { Debug.Log("Server successfully started"); } void uLink_OnConnectedToServer () { Debug.Log("Now connected to server"); Debug.Log("Local Port = " + uLink.Network.player.port.ToString()); } void uLink_OnPlayerDisconnected(uLink.NetworkPlayer player) { uLink.Network.DestroyPlayerObjects(player); uLink.Network.RemoveRPCs(player); } void uLink_OnFailedToConnect(uLink.NetworkConnectionError error) { Debug.LogError("uLink got error: "+ error); } void uLink_OnPlayerConnected(uLink.NetworkPlayer player) { Debug.Log("Player connected from " + player.ipAddress + ":" + player.port); } }

5. Save your changes to the script. 6. Drag and drop the ConnectionGUI script to the Main Camera in the Hierarchy View. Select the Main Camera game object and verify that the script appears in the list of components in the Inspector View. 7. Press the play button. You should see something like in the picture.

8. Click the Start Server button, and the following should appear (note that your IP address may differ.)

4

9. Open the console window by Window >> Console. This is where you can see all the debug output from the ConnectionGUI script. Make sure that there are no errors. There should be one line in the console saying "Server successfully started". 10. Press the play button in Unity again to stop the execution. 11. Save your scene by File >> Save Scene, and name it "MainGame". This is a good time to read the code in the ConnectionGUI script in detail. You should note one minor syntax detail that is different when using uLink instead of Unity's own network library. This is that all network specific callbacks must begin their names with "uLink ", like so: uLink_OnServerInitialized(). Unity does not force you to put scripts in a Scripts folder - we chose this layout simply to keep things organized. uLink is built to support the same API and features as Unity's built-in network. This is because we want the transition to uLink to be as painless as possible, both for the project and for the programmer. Note that uLink has a few additional callbacks compared to Unity's built in network. With uLink it is possible to use much more advanced network features. The best way to learn more about the Network class and the different callbacks that are available is to check out the uLink manual and API at http://unitypark3d.com/support/. There you will find all the info you need to become an expert uLink user.

5

Starting a client

The code for starting a client is already included in the ConnectionGUI script. One tricky part when testing network code is to run a client and a server at the same time on one computer. This tutorial will show how to do this by using two Unity editors simultaneously.

5

1. Open Unity's preferences and check the box Show Project Wizard at Startup if it is not already checked. 2. Now close Unity. Since Unity only allows one project to be open in the editor at a time, we will make a copy of the project folder to open in another instance of the editor. 3. Navigate to the directory where your Unity project is stored. Make a copy of the project folder uLink Tutorial 1. Name the copy "uLink Tutorial 1 Client". 4. We will now open two Unity editors. In Windows, this is done by simply opening Unity twice. On a Mac, it is somewhat more tricky; see the notes below. 5. Open one Unity editor with project folder uLink Tutorial 1 and the other with project folder uLink Tutorial 1 Client. Open the MainGame scene in both editors by double-clicking it in the Project View. 6. Press the play button in both editors. Place the editor windows beside each other to make it easy to see both at the same time. 7. Start one instance as a server by clicking the Start Server button, and the other as a client by clicking the Connect button. As long as the testing is done on one machine there is no need to alter neither the IP address nor the port number. 8. Verify that the console at the server reports no errors, like you did in the previous section. The output should say something like "Player connected from 127.0.0.1:55418".

In order to open several instances of the Unity editor in Mac OS X, first open one Unity editor in the usual way. Then, navigate in the file system to where Unity is installed (the default location is in the Applications directory). Right-click the Unity application and select Show package contents. Open the Contents folder and then the MacOS folder. Double-click the Unity binary to open a new Unity instance. A terminal window will appear - do not close this window! It can be closed when Unity has exited. As an experiment, try connecting from the client when the server is not started. After 15 seconds there will be an error message in the client's console. The callback uLink_OnFailedToConnect has been called.

6 Network-aware objects and state synchronization We will now attempt to make a minimal game scene and instantiate a cube for every connected client. The cube will be a network-aware game object that gets its state synchronized across the network. This means that when a client changes its cube, the changes will be seen by all other clients as well. 1. Close the Unity editor that shows the project uLink Tutorial 1 Client. Keep the other editor open. 2. Create a new folder in the Project View and name it "Resources". 3. Create a new prefab and name it "PlayerAvatar", by Assets >> Create >> Prefab. 4. Place your new prefab in your Resources folder. 5. Create a new cube game object, via GameObject >> Create Other >> Cube. 6

6. Drag the cube from the Hierarchy View to the PlayerAvatar prefab. 7. Delete the cube game object from the Hierarchy View. 8. Create a new plane and name it "Plane", via GameObject >> Create Other >> Plane. Your plane's parameters should be: Position: (0, 0, 0), Rotation: (0, 0, 0) and Scale: (10, 10, 10). 9. Create a directional light, via GameObject >> Create Other >> Directional Light. Your light's parameters should be: Position: (0, 15, 0), Rotation: (25, 0, 0), Scale: (1, 1, 1). In the light component, set Shadow Type to Soft Shadows. 10. Save your scene. The picture below shows the state of the Unity editor at this point.

11. Select the PlayerAvatar prefab and add a uLinkNetworkView script component to it. To do this, locate the script in Plugins >> uLink >> Basic Scripts in the Project View and drag it to the Inspector View of PlayerAvatar. 12. Change the Observed property of the uLinkNetworkView component to PlayerAvatar's Transform component by dragging the Transform component from the top of the Inspector View and dropping it on the Observed field.

7

13. Add a Rigidbody component to your PlayerAvatar prefab, via Component >> Physics >> Rigidbody. 14. Create a new, empty game object and name it "SpawnLocation". Your new game object's parameters should be Position: (0, 5, 0), Rotation: (0, 0, 0) and Scale: (1, 1, 1). 15. Create a new C Sharp Script file in the Scripts folder and name it "Instantiate". 16. Open the file and write following code. using UnityEngine; public class Instantiate : MonoBehaviour { public GameObject PlayerPrefab; void uLink_OnConnectedToServer() { uLink.Network.Instantiate(PlayerPrefab, transform.position, transform.rotation, 0); Debug.Log("Network aware game object is now created by client."); } }

17. Add the new script to your SpawnLocation game object by selecting SpawnLocation and then drag-and-dropping the script in the Inspector View. 18. Change the Player Prefab property of the Instantiate component to PlayerAvatar. 19. Save your scene. The network aware object is now ready to be tested.

8

VERY IMPORTANT! All prefabs that are to be instantiated as network-aware objects MUST to be placed in the Resources folder when using uLink. Memorize this now to avoid this problem later when making your own game!

7

Testing the network-aware object

You will now once more use several Unity editors simultaneously in order to test your game. 1. Close all Unity editors. 2. Remove the folder for uLink Tutorial 1 Client. It will not be needed anymore. 3. Make two copies of the folder uLink Tutorial 1 and name them "uLink Tutorial 1 Player 1" and "uLink Tutorial 1 Player 2". 4. Start two Unity editors, one with the project uLink Tutorial 1, and one with uLink Tutorial 1 Player 1. Press the play button in both editors. 5. Start the server in the editor with the project uLink Tutorial 1 and connect the client in the other editor. Place the editors beside each other. 6. You should see a cube in both editors.

7. Try changing the Y-coordinate for the PlayerAvatar(Clone) game object to 5 in the client. You should be able to see that the cube falls down on the surface in both editors. 8. Now, try changing the Y-coordinate for the PlayerAvatar(Clone) game object to 5 in the server instead. The cube should not move because the server is not the owner of the object in the eyes of uLink; the cube is owned by the client. 9

9. Start a third Unity editor with the project uLink Tutorial 1 Player 2, press play, and connect it as a client to the server. Verify that two cubes are now visible in all editors. 10. Stop all editors. 11. Add a "Toss me" button for both clients by changing the Instantiate script to contain the following code in both the two client editors. Do not change the name of the script! using UnityEngine; public class Instantiate : uLink.MonoBehaviour { public GameObject PlayerPrefab; private GameObject playerAvatar; void uLink_OnConnectedToServer() { playerAvatar = uLink.Network.Instantiate(PlayerPrefab, transform.position, transform.rotation, 0); Debug.Log("Network aware game object is now created on client"); } void OnGUI() { if(GUI.Button(new Rect(20,100,70,50),"Toss me")) { playerAvatar.transform.position = new Vector3(0,3,0); playerAvatar.transform.rotation = new Quaternion(50,50,50,0); } } }

12. Start the server and start the two clients. Connect the clients to the server. 13. Test the Toss me button and verify that it can toss the cube for each player.

uLink has new and unique support for making games with authoritative servers, meaning that the server owns all objects and acts as a judge for all network actions. For example, with an authoritative server, clients cannot themselves send state-syncs to the server; only the server can send to clients. This is the kind of architecture most commercial multiplayer games use because it is more secure. This tutorial however, does not use an authoritative server. Instead the clients send state-syncs for the objects they have instantiated, one cube each.

8

Remote procedure calls

Another very important concept in uLink, just like in Unity's network library, is remote procedure calls (RPCs). By using RPCs, it is possible to make method calls over the network to a single receiver or to all connected clients, which is called broadcasting. In this tutorial the broadcasting technique will be used in a basic example of how to use RPCs. 1. Stop all running editors. 2. Create a new C Sharp Script named "RPCTest" in the Scripts folder in the editor that has the uLink Tutorial 1 server project open. 3. Replace the contents of the script with the following code.

10

using UnityEngine; using System.Collections; public class RPCTest : uLink.MonoBehaviour { void OnGUI() { if(GUI.Button(new Rect(20,170,80,50),"Send RPC")) { networkView.RPC("HelloRPC", uLink.RPCMode.Others, "Hello uLink. Timestamp = " + System.DateTime.Now.Ticks); } } [RPC] void HelloRPC(string arg1) { Debug.Log("Got RPC containing: " + arg1); } }

4. Add your new script as a component in the PlayerAvatar prefab, which is located in the Resources folder. 5. Perform step 2, 3 and 4 in the other two editors as well. 6. Now, start the server and start the two players. Connect the players to the server as before. 7. Push the new button named Send RPC in any one of the editors. 8. Verify that you get an output message in the other editors' consoles saying that an RPC was received. The RPCTest script inherits from the uLink.MonoBehaviour class. This is important and makes it possible to use the networkView property in the code and get the uLink version instead of the Unity version of the NetworkView component. Any method that is to be called as an RPC has to be marked with the [RPC]attribute. You can see this in the code sample at the line above the method HelloRPC().

9 Conclusion Congratulations! You have now tried the basic, most important tools of uLink, and are now ready to begin building the networking part of a more advanced game in Unity. You have learned how to start a server, how to connect clients, and how to handle two of the most important tools for networked games, state synchronization and remote procedure calls. If you want to examine the code for a somewhat more advanced game, just download and test one of the free demo games at uLink's website, http://www.unitypark3d.com.

11