Unity Network: Introduction to Networking in Unity Tutorial

Unity Network Scripting:

In this Unity Network scripting video tutorial we’ll be making an online multiplayer environment in which players can move around, see and bump into each other, and send messages across the network to update other players with information about a change (i.e.: in the environment). We have also included a web player version of this scripting demo to start networking with your friends.

Download of unity source files contains Project files and Networking Web Build Demo

Test out this demo online

What is covered in this Unity tutorial:
- NetworkView Component
- RPCs (Remote Procedure Calls)
- Initializing and registering a host to the Unity Masterserver
- Fetching a list of hosts
- Connecting to a hosted game

Unity Network

Leave Comment

Discussion

156 Responses to “Unity Network: Introduction to Networking in Unity Tutorial”
  1. Posts: 2

    Yay, first!
    This tut is great, really convenient as i was getting around to this with my game,

  2. Posts: 2
    Ehab Charek says:

    thank you very much!!! :D
    but I would like to know (and yes I do realize that this is unity cookie, butt…) is it possible to be done in blender?
    sorry if I’m bothering you with this question, but I’ve been dying to figure out how to do this in blender for many months but no success :P

    • Posts: 109

      Not by default, no. However, there is something called RakNet-Python, which is a Python library for RakNet, the open-source networking backend Unity uses as well. You could use this and call it from a Blender Python script.

      -Patrick

      • Posts: 11
        David Lee says:

        You have no idea how much I appreciate this tutorial, I have been wanting to see something like this since I got unity. Also, You have NO IDEA how many years I thaught you couldnt do that with Blender. (which would, I think, be a good scripting tutorial for blender) :)

        thanks,
        Sasbian

  3. Posts: 46

    Looks interesting. Am I supposed to be able to connect with other people with the online demo?

    Jeremy Deighan

  4. Posts: 14
    Mike Pegelow says:

    Thanks for the tutorial!
    I have 2 questions:

    Is it possible to attach a texture to the buttons and let’s say i want to make a browsergame, can i use the masterserver for that?

  5. Posts: 5
    YoungApprentice says:

    Thank you so much. This tutorial was amazing.

    • Posts: 1
      Terje says:

      Great tutorial. It scared away alot of my networking ghost :P I will try to apply this to my next game.

  6. Posts: 5
    Steve Schiro says:

    Thats great. Is it similar if I want to just connect to a nearby device? Or do you have to connect to a server to do that kind of thing.

    • Posts: 109

      Hey Steve,

      If you want to do something with nearby devices you’d probably need to use some kind of Bluetooth service. I’ve never done anything like this though, so my knowledge on this is pretty much non-existent I’m afraid.

      -Patrick

      • Posts: 8
        Ryan M. says:

        What about using local LAN networks?

      • Posts: 109

        Hey Ryan,

        The Network.Connect() function is overloaded; you can also use it to connect to a (local) IP address and port.

        -Patrick

  7. Posts: 4

    how can i get this to c#??

    if(hostData){
    for( int i =0; i<hostData.Length -1; i++){
    GUI.Button(new Rect(400, 400, 50, 30), hostData[i].gameName);

    }

    • Posts: 109

      Hey Arderkuoi,

      The code you provides is already in C#, what seems to be the problem?

    • Posts: 1
      Bladesfist says:

      if(!(hostdata == null))
      {
      for(int i =0; i < hostdata.Length; i++)
      {
      GUI.Button(new Rect(btnX * 1.5f + btnW, btnY * 1.2f + (btnH * i), btnW * 3f, btnH * 0.5f), hostdata[i].gameName);
      }
      }

  8. Posts: 5
    gamenovice says:

    Hey Patrick,

    Awesome site! When I first heard of this site, seeing from blender cookie, I knew this site was going to be good.

    There were a few things about unity that had me really con vexed, either that or I was overreacting, and these are the things that I would like to know how to do in unity, if possible:

    get a character(even a box) to swim,

    make a basic cinematic event

    crossfading animations in script (like having a battle pose ready in the upper body, but strafing at the same time in the lower body)

    any one of those would make my day!

    Thank you for listening,
    gamenovice

      • Posts: 33
        Gary Parkin says:

        I’d like to add a few too!
        More GUI stuff like building a full menu. And how would you switch it on and off?

  9. Posts: 2
    James Tadeo says:

    Thanks for the tutorial Patrick. I like how you developed the concepts of networking.

    • Posts: 57
      Wes Burke says:

      Hi Clarissa – Yes and Subscribers also have access to the exclusive content on this site and any other site in the network. ;)

  10. Posts: 5

    Thank you very much!
    There wasn’t any good tutorial on how to do a network game, and now Yay!

  11. Posts: 4
    Lucas Kerbs says:

    How would I make it so that each player could have their own camera?

    • Posts: 109

      The active Camera (Main Camera) is the first enabled one tagged “MainCamera”, so you could do something along the following lines:

      - Add a Camera to the Player prefab as a child of your character.
      - In the SpawnPlayer() function, do the following:
      Destroy(Camera.main); //Remove old Main Camera
      var player:GameObject = Network.Instantiate(playerPrefab, spawnPos, spawnRot, 0);
      if(player.networkView.isMine){ //check to make sure it’s out player being spawned
      var playerCam:Camera = player.transform.Find(“Camera”); //find child named “Camera”
      playerCam.tag = “MainCamera”; //set it’s tag so it becomes the active one
      }

      This is untested code though, so please forgive any errors. ;)

      -Patrick

      • Posts: 4
        Lucas Kerbs says:

        Two error that I can’t seem to fix:
        var player:GameObject = Network.Instantiate(playerPrefab, spawnPos, spawnRot, 0);
        Here I get: The best overload for the method ‘UnityEngine.Network.Instantiate(UnityEngine.Object, UnityEngine.Vector3, UnityEngine.Quaternion, int)’ is not compatible with the argument list

        var playerCam:Camera = player.transform.Find(“Camera”);
        Here I get: ‘(UnityEngine.GameObject, UnityEngine.Transform, UnityEngine.Transform, int)’. (BCE0017) (Assembly-UnityScript)

      • Posts: 109

        Hey Lucas,

        The snippet I provided is incomplete psuedo-code, so you’ll have to replace the spawnPos and spawnRot with your desired position and rotation.
        On the second line I made an error. It should be:
        var playerCam:Transform = player.transform.Find(“Camera”);
        since Transform is transform.Find()’s return type.

        Happy holidays!
        -Patrick

  12. Posts: 1
    IrishStorm says:

    Great tutorial! I am having an issue with “BCE0019: ‘HavePublicAddress’ is not a member of ‘Network’. ” and “BCE0019: ‘HavePublicAddress’ is not a member of ‘Network’.”
    Here is the code
    function startserver()
    {
    Network.InitializeServer(4, 25000, !Network.HavePublicAddress);
    MasterServer.RegisterHost(GameName, “GameName”, “Description”);
    }
    and the version i am using is 3.2 0f4
    Any help would be much appreciated, as i am new to unity xD

    • Posts: 109

      Hey IrishStorm,

      HavePublicAddress is a function, so you’ll need to call it as such using parenthesis. =)

      “Network.InitializeServer(4, 25000, !Network.HavePublicAddress());”

      -Patrick

  13. Posts: 5
    bk9iq says:

    Thanks Patrick for the amazing tutorial …
    I just have some questions:
    1- Why do we need to use RPC if we have networkView ? I mean are there any limitations or things we can’t do with networkView?

    2- I changed the box that we had to a character (model)… I am trying to animate it just as “walk” when the player presses any Horizontal or Vertical button but one player presses something the second player doesn’t see the animation… I used ::

    if(this.networkView.isMine)
    {
    Player.Move(Vector3(Input.GetAxis(“Horizontal”) * 5 * Time.deltaTime, -1, Input.GetAxis(“Vertical”) * 5 * Time.deltaTime));

    if(!Input.GetAxis(“Horizontal”) && !Input.GetAxis(“Vertical”)){networkView.animation.CrossFade(“IdleLookAround”);}

    else{networkView.animation.CrossFade(“Walk”);}
    }

    I have this in the Player Script … Inside the Update function… however it is not reflecting the changes in the player animation … is there any easy way of managing that?

    Thanks again …

    • Posts: 109

      Hey there,

      The reason we have RPCs is for a couple of reasons. The most important one is that NetworkViews immediately send out their data to all other parties. In most real-life cases however, you’ll probably want to use an authorative server approach, where you send a message to the server (i.e.: @RPC MovePlayer(gameObject)), after which the server verifies the action and updates all of the other players (either through a NetworkView or another RPC call).
      Also, for every component you wish to observe (transform, animations, materials, etc.) you’ll need another NetworkView Component. This can get a bit cluttered and bulky, so you could just as well use that one NetworkView to, say, check and update the position, and also use it as your RPC ‘portal’ to send updates on animations for instance.

      I think this also pretty much answers your second question:
      You could use either a second NetworkView Component to observe the Animation Component, or use RPCs to update the other players.

      Hope this helped!
      -Patrick
      PS: You don’t need to use the ‘this’ keyword in your scripts; all it does is refer to the script Component, which it also does by default when calling upon another component (every component can call all other components on the same GameObject). Hence, ‘this.transform.position’ is the same as ‘transform.position’.

      • Posts: 5
        bk9iq says:

        Thanks so Much Patrick … This was really helpful … I used RPC and animation worked for me.. after that I tried to reduce the lag but couldn’t find anything online so I read the manual.. I changed the SendRate under the “Edit>>Project Settings>> Network” from 15 to 50 and now it is not lagging at all…
        Thanks again Patrick .. I can’t wait for your next tutorial :)
        Happy New Year …

      • Posts: 109

        Oh good call! I probably should’ve mentioned the sendrate in the tutorial as well.

        Happy new year!
        -Patrick

  14. Posts: 33
    Gary Parkin says:

    Wow, Patrick. I think you hit on a great subject for more tutorials.
    And congrats for being up at 3AM to record it. I’d have sounded like death warmed over at that hour.
    This tutorial opened up a lot of possibilities too, as well as some much needed information.

    Thanks so much.

    • Posts: 109

      Hey Gary!

      Ha, what can I say, I prefer working at night; zero distractions. =) Also, in reply to your tutorial suggestion, it’s already in the planning for the new year!

      Happy new years!
      -Patrick

      • Posts: 33
        Gary Parkin says:

        Thanks Patrick
        Happy New year!

        ~Gary

  15. Posts: 1
    Ben High says:

    Hey. I am on a rather slow Internet connection and the video is taking a wile to load. Does anybody have either the video for direct download or a premade game?

    • Posts: 109

      Hey Sharpclaw,

      Becoming a Citizen would offer access to video and source downloads like your describing. Perhaps it would be something to consider? =)

      Happy new years!
      -Patrick

      • Posts: 33
        Gary Parkin says:

        Patrick is correct, sharpclaw. There are so many unseen perks, and the membership is cheap compared to other sites.
        I joined for a year to see if I’d like it, but you can join for as little as a month.
        I’m staying a supporter as long as I can.

        Happy New Year.

  16. Posts: 1
    skeptika says:

    Any chance you could use Photon in future tuts? It’s free for up to 100 concurrent users (so it keeps with the free spirit here and can be used in free Unity) which should cover just about any planned gametype outside of a huge commercial release. In addition, from what I can tell, seems a lot more capable than the built in Unity networking. Just a suggestion, great tutorial and thank you!

    • Posts: 109

      That’s actally not a bad idea! I’m not sure when or how in-depth it’d be, but I could imagine covering other networking possibilities such as Photon and SmartFox Server. Thanks for the suggestion!

      -Patrick

  17. Posts: 9
    Richard Ward says:

    Thanks for this! I made myself a little in-game chat setup as soon as I saw this, and it works great – at least with two people connected, I haven’t had chance to test it with any more yet.

  18. Posts: 1
    Ed says:

    Wow.. I was copying what you did to try and pick it up. I mistyped ‘hostData’ as ‘hostdata’ on line 33.

    When I tried to run the code in Unity, I didn’t get a debugger error. I didn’t get anything at all, except for a Windows message to tell me that Unity had crashed!

    I tried it twice, and the same thing happened… is this normal?

    Excellent tutorial by the way!

    • Posts: 109

      Hmm, I’ve had similar experiences, but it’s definitely unintended behaviour. I can’t try this out right now, but it may be worth a bug report. And thanks!

  19. Posts: 2
    Paulo says:

    Were i can find the var isMine? “if (NetworkView.isMine)” on Movement control.

    • Posts: 2
      Paulo says:

      never mind my bad networView and not NetworkView:)

  20. Posts: 5
    bk9iq says:

    Hey Patrick… let’s say I have two players in my game … I am trying to make player 2 loses health when player 1 presses “F” (When Close) … My problem is that The current health I made as a variable.. so it is available to all the players in the network .. but I don’t know how to change player 2 current health without affecting player 1 or any other player health … I mean how can player 1 change player 2 health.. How do I make the health loss specific to player 2 only …

    Thanks very much …

    • Posts: 109

      Hi Bk9iq,

      I think the easiest way to do this is to use trigger collisions to detect which player you’re attacking. To make this work, each player will require a tag ‘Player’, a Collider that’s set to trigger (I’d suggest using a Sphere Collider; this way you’ll have a nice radius of detection) and a kinematic Rigidbody. Then you could do something like this (non-optimized and non-tested code): http://pastebin.com/bzymAijv

      Hope this helped!
      -Patrick

  21. Posts: 1
    Ian Jones says:

    Thanks for the tutorial! Really great intro and sums everything up nicely. My only suggestion would be to point people to the main Unity docs to gain the bigger networking picture.

  22. Posts: 2
    Sergio Osma says:

    Thanks a lot, its great, but I ask you for a new tutorial, about making the game really network, I mean, make all the process, set ports, firewall, etcetera for play with two computers on the web and not only in my own network.

    • Posts: 109

      Hi Sergio,

      The ‘game’ created in this tutorial is already playable over the web and not limited to your own network. =)

      -Patrick

  23. Posts: 2
    Jon Diericks says:

    Fantastic tutorial! This is helping me alot. Will you be doing a tutorial on expanding this one? such as for Chating? If not, how would i go about doing this?

  24. Posts: 3
    MeMyself says:

    thank you thank you thank you for this tutorial, I finished it and tweaked it so each cube uses its own camera
    first make a cam script

    var cam:GameObject;
    public function Start()
    {
    //get rid of all unrelated cameras
    for(var i = 0; Camera.allCameras.Length > i; i++)
    {
    if(networkView.isMine == false)
    {
    Destroy(cam);
    }
    }
    }

    then make a camera , tag it as Main camera , and drop it into your player prefab. then drop the same camera into the cam variable slot of the cam script.

    that makes you have your own camera, then i also tweaked the movement script’s update function to this.

    function Update () {
    if(networkView.isMine)
    {

    if(Input.GetAxis(“Vertical”) != 0)
    {
    if(Input.GetAxis(“Vertical”) > 0)
    {

    transform.Translate(Vector3.forward * speed * Time.deltaTime ) ;
    }
    if(Input.GetAxis(“Vertical”) < 0)
    {

    transform.Translate(Vector3.back * speed * Time.deltaTime ) ;
    }

    }
    if(Input.GetAxis("Horizontal") != 0)
    {
    transform.Rotate(Vector3(0, Input.GetAxis("Horizontal")* speed *Time.deltaTime,0)) ;
    }
    }

  25. Posts: 3
    MeMyself says:

    but seriously THANK YOU !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

  26. Posts: 3
    MeMyself says:

    oh and make sure when you add the camera to your prefab that you don’t replace the prefab but child the cam to the cube instead. you may have to drop the prefab on the stage then add the cam to it then replace original prefab.

  27. Posts: 2

    over www i see the button , but i cant join . In local lan i can join . What must be changed to get it work over www? sorry for my bad english

  28. Posts: 1
    Rennomus says:

    Wow.. Super awesome tutorial!, best free introduction tutorial on multiplayer networking I have seen so far. Thank you so much!

    I’ll definetly bookmark this site, and check for future tutorials.

    Cheers! :)

  29. Posts: 8
    Markus B says:

    @MeMyself
    I also experimented with two cameras, and it works, so far, but even with your code, i got this message:

    There are 2 audio listeners in the scene. Please ensure there is always exactly one audio listener in the scene.

  30. Posts: 8
    Markus B says:

    And Debug.Log(Camera.allCameras.Length); doesnt show up in the console… strange

  31. Posts: 1

    There seem to be a couple errors i control both

    var groundSpeed : float; //Force applied when grounded
    var airSpeed : float; //Force applied when in air
    var jumpSpeed : float; //Force applied when jumping
    var horizontalRotationSpeed : float; //Horizontal rotation speed of the player
    var onGroundDrag : float; //Rigidbody drag used on ground
    var inAirDrag : float; //Rigidbody drag used in air

    private var onGround : boolean = false; //Determines whether the player is grounded or in air
    private var jump : boolean = false; //Determines whether the player should jump
    private var rb : Rigidbody; //Reference to the rigidbody component of the game object
    private var t : Transform; //Reference to the transform component of the game object

    function Awake() {
    rb = rigidbody; //Cache rigidbody component
    t = transform; //Cache transform component
    gameObject.layer = 8; //Set gameObject layer to Player layer
    }

    //Check for one-off input in the Update loop since checking for input in FixedUpdate can lead to lost input events
    function Update(){

    if(networkView.isMine) {

    //Since we’re not applying rotation as torque, we don’t need to do it in FixedUpdate
    rb.MoveRotation(rb.rotation * Quaternion.Euler(Vector3.up * Input.GetAxis(“Mouse X”) * horizontalRotationSpeed * Time.deltaTime));
    if(Input.GetKeyDown(KeyCode.Space)) {
    if(onGround) {
    jump = true; //The player will jump when next FixedUpdate is called
    }
    }
    }

    //Apply physics forces in FixedUpdate
    function FixedUpdate() {
    //Calculate and normalize movement vector
    var movement = Vector3(Input.GetAxisRaw(“Horizontal”), Input.GetAxisRaw(“Vertical”), 0);
    if(movement.sqrMagnitude > 1)
    movement.Normalize();

    //Add force in the direction of movement
    rb.AddRelativeForce(movement.y * Vector3.forward * ((onGround) ? groundSpeed : airSpeed));
    rb.AddRelativeForce(movement.x * Vector3.right * ((onGround) ? groundSpeed : airSpeed));
    if(jump) {
    rb.AddForce(t.up * jumpSpeed); //Add upwards force to make player jump
    onGround = false; //Player is no longer grounded
    jump = false;
    rb.drag = inAirDrag; //Change rigidbody drag to allow for better movement in air
    }
    }

    //Check for collisions to determine when the player is on the ground
    function OnCollisionEnter(collision : Collision) {
    var collisionAngle = Vector3.Angle(collision.contacts[0].normal, Vector3.up); //Calculate angle between the up vector and the collision contact’s normal
    if(collisionAngle < 40.0) { //If the angle difference is small enough, accept collision as hitting the ground
    onGround = true; //Player is grounded
    rb.drag = onGroundDrag; //Restore original drag value
    }
    }
    }

  32. Posts: 1
    Bruno says:

    Hey,
    Are any difference to program in JS vs C#??

    Or is only your personal choice?

    Thanks =)

  33. Posts: 3
    Daniel says:

    Hi Patrick!

    First of all thank you for a great tutorial! Helped me a lot…
    I managed to build it and get 3 connections in my LAN, however could not get someone from outside my LAN to connect to me, any ideas? (Although they did see the button ‘Tutorial game name’ when they refreshed the host).

    You said for a ‘full’ overview of networking you would need 3-4 tutorials, are you planning on making any of them?

    Thanks again.

    Daniel

    • Posts: 3
      Daniel says:

      btw, just did some port forwarding so a friend could connect through the net!!! worked!! :) thanks again!!
      Still looking forward to those additional networking tutorials for the complete picture!!
      Do you still think you might do them??

      All the best,
      Daniel

      • Posts: 109

        Hi Daniel,

        Glad you got it working! I might do one or two more on this subject sometime, but network coding isn’t really my strong suit. There’s a lot of nitty-gritty details to get lost in, especially when making a game meant for release. For instance, you’d probably try and make as much stuff as possible server-sided, including otherwise simple things like character movement. However, sending a request to the server and waiting for a response takes (too much) time, so you’d need to execute it both on the client and server sides, compare the results and then if needed interpolate to the serverside result. This is a relatively simple example, but there are multiple ways to handle stuff like this. And then there’s things like firewalls, security sandboxes, and plenty more I’m sure.
        Don’t get discouraged though! I’m sure it’s all perfectly manageable if you take the time to really get into it. I just haven’t done that myself yet. ;)

        -Patrick

  34. Posts: 3
    Daniel says:

    Thanks for the great reply Patrick :) (for some reason I couldn’t reply directly, had to make a new post).
    Yes I read about the other issues with networking and I agree it’s a matter of knowledge to get everything right :)

    Thanks again, keep up the great work, and have a great day. :)

    Daniel

  35. Posts: 2
    Xeus says:

    Great tut
    but i get an error
    error CS0117: `Network’ does not contain a definition for `InitializeServer’

    Here’s the code:
    Network.InitializeServer(4, 25000, !Network.HavePublicAddress());

    I’ts c# can u help plz

    • Posts: 2
      Xeus says:

      Oh solved it
      named the class Network xD
      but thx

  36. Posts: 1
    GTGD says:

    Thank you for sharing this with us, it’s an outstanding tutorial! I’ve learnt a lot by watching this tutorial and I’m intending to make use of Unity’s Master Server in my next series.

  37. Posts: 5
    Freeze says:

    I copied the script exactly but the buttons won’t show up? What am I doing wrong???

    • Posts: 109

      Hi Freeze,

      It’s hard to say without seeing the script. Did you attach the script to an object? If so, please post your script on a site like pastebin.com and put the link to it here so I can help you further.

      -Patrick

  38. Posts: 5
    Freeze says:

    I attached it to an empty. here is the script so far. There are no errors the buttons just won’t show up.

    var btnX : float;
    var btnY : float;
    var btnH : float;
    var btnW : float;
    var gameName:String = “Robbie_Productions”;
    function Start(){
    btnX = Screen.width * 0.05;
    btnY = Screen.width * 0.05;
    btnH = Screen.width * 0.1;
    btnW = Screen.width * 0.1;
    }
    function startServer(){
    Network.InitializeServer(4, 25001, !Network.HavePublicAddress);
    MasterServer.RegisterHost(gameName, “RobbieGame”, “Yaaay”);
    }
    function refreshHostList(){
    MasterServer.RequestHostList(gameName);
    yield WaitForSeconds(1.5);
    Debug.Log(MasterServer.PollHostList().Length);
    }
    //Messages
    function OnServerInitialized(){
    Debug.Log(“Beginning Your Game”);
    }
    function OnMasterServerEvent(mse : MasterServerEvent){
    if(mse == MasterServerEvent.RegistrationSucceeded){
    Debug.Log(“Registered Server!”);
    }
    }
    //GUI
    function OnGui () {
    if(GUI.Button(Rect(btnX, btnY, btnW, btnH), “Start Server”))
    {
    Debug.Log(“Starting Server”);
    startServer();
    }
    if(GUI.Button(Rect(btnX, btnY * 1.2 + btnH, btnW, btnH), “Refresh Hosts”))
    {
    Debug.Log(“Refreshing”);
    refreshHostList();
    }
    }

    Did I copy it down Wrong???

    • Posts: 109

      Hey Freeze,

      The GUI function should be called OnGUI(), rather than OnGui(). =)
      Also, please do use a site like pastebin next time, as it prevents character and formatting errors.

      -Patrick

      • Posts: 5
        Freeze says:

        Thank You So Much!!! This Is an amazing tutorial and a great website to learn about unity

      • Posts: 109

        No problem; glad I could help! And thank you for the kind words! =)

        -Patrick

      • Posts: 7
        Jared Black says:

        I did the exact same thing today. Good thing I didn’t have to post it again.

  39. Posts: 7
    Jared Black says:

    I have a problem. I want to use a first person controller, but at the part where in the movement script, you did
    if(networkView.isMine). On the first person controller, I’m not sure where to put that code in the CharacterMotor Script. I really want to get this working.

    • Posts: 7
      Jared Black says:

      …I still have this problem. A reply would be nice ;). I know you’re around because I saw you on Blender Guru!

      • Posts: 109

        Hey Binxblack!

        Sorry my late response; I completely forgot about this one! In the future, please feel free to send us a support ticket instead; we get daily reminders on those if we slack off. ;)

        The if(networkView.isMine){} check just makes sure that whatever if placed between the curly braces {…} is only executed on the player’s own object. In most cases, that’s gonna be everything, from catching input to tinting the screen red when your hp drops below a certain threshold for instance.

        So with the FPSController for example (which is what drives the CharacterMotor I think, though I could be wrong), you’d have the structure of:

        function Update(){
        if(networkView.isMine){
        var directionVector = new Vector3(Input.GetAxis…..);//etc
        }
        }

        Hope this helped and sorry again for my late response!
        -Patrick

      • Posts: 109

        In this case you’d want to create a new Vector3 based on your inputs. The structure is:
        var someVector:Vector3 = new Vector3(x,y,z),
        so to catch the X- and Z-axis input we can use:
        var directionVector:Vector3 = new Vector3(Input.GetAxis(“Horizontal”), 0, Input.GetAxis(“Vertical”));

        -Patrick

  40. Posts: 1
    Christian Cantrell says:

    I followed this tut but networkView.IsMine seems to not be working or doing something weird both players can move but they move each other instead of themselves can someone help me out (Code Included below)

    using UnityEngine;
    using System.Collections;

    public class MovementScript : MonoBehaviour {
    public CharacterController cc;

    private Vector3 myDirection = Vector3.zero;

    public float movSpeed = 0.1f;
    public float gravity= 20.0f;
    public float jumpSpeed = .1f;

    // Use this for initialization
    void Start () {
    cc = GetComponent();

    }

    // Update is called once per frame
    void Update () {
    if(networkView.isMine){
    myDirection = new Vector3(Input.GetAxis(“Horizontal”),0,Input.GetAxis(“Vertical”));
    myDirection = transform.TransformDirection(myDirection);
    myDirection *= movSpeed;
    if(Input.GetButton(“Jump”)){
    myDirection.y = jumpSpeed;
    }

    myDirection.y -= gravity * Time.deltaTime;
    cc.Move(myDirection);
    }
    }
    }

  41. Posts: 5

    On when you start a game in 5:28 time you have start server button but i dont have one why? :(

  42. Posts: 5

    I got problem :( where can i found movement script? I got first person controler prefab from unity assets and hows the movement script called in FirstPersonController prefab?

  43. Posts: 5

    I got other problem when i connected with 2 langs,i can controll other player, i do everything you do but still got problem

    • Posts: 109

      Hey Mode,

      It’s hard to tell the problem without seeing the actual code, but my initial guess would be the problem lies in the “if(networkView.isMine)” check. If you’re still having problems with it, please feel free to upload the code to pastebin.com and share the link here so I can take a look at it.

      As for your other question, the MovementScript was a small custom script made by me; it’s not a standard asset.

      -Patrick

  44. Posts: 16
    Nico says:

    can unity have LAN networked games?

    • Posts: 109

      Hi Nicomay,

      The Network.Connect() function is overloaded; you can also use it to connect to a (local) IP address and port.

      -Patrick

  45. Posts: 1
    Thinkorswim says:

    If somebody connects to the server and then the scene changes will we be still connected, because it is not working properly for me? Great tutorial anyways :)

    • Posts: 109

      Hey Thinkorswim,

      I haven’t ever really tried that so I’m not sure, but I would assume that all network connections remain intact. I think your best bet in this case would be to post a topic on the Unity forums and explain the problem in more detail there.
      Though as a quick test-scenario I could imagine the following set-up:

      Scene A:
      - Make sure 2 players are connected
      - Both enter Scene B

      Scene B:
      - Have player 1 send a RPC-call to all connected players, where you can catch this in player 2′s game to confirm the connection still exists.

      An example of this RPC-function could be as simple as Debug.Log()ing “I got called!”.

      Sorry I couldn’t be of more help and good luck!

      -Patrick

  46. Posts: 13
    sarkhamy says:

    hi there! one question! Whenever I try to make a GUI in any of my games… it doesn’t show up. Why is this?

  47. Posts: 1

    Hi there .I have a problem with running the code .The Start Server Button works fine but the Refresh Host gives me this message
    NullReferenceException: Object reference not set to an instance of an object
    Boo.Lang.Runtime.RuntimeServices.InvokeBinaryOperator (System.String operatorName, System.Object lhs, System.Object rhs)
    NetworkManager.Update () (at Assets/Game Assets/Scripts/TestScipts/NetworkManager.js:36)
    and the second one repeats itself until i stop the game
    The code is:
    var gameName:String = “CFS_Network_Test_Game”;

    private var refreshing : boolean;

    private var btnX:float;
    private var btnY:float;
    private var btnW:float;
    private var btnH:float;

    function Start()
    {
    btnX = Screen.width * 0.05;
    btnY = Screen.width * 0.05;
    btnW = Screen.width * 0.1;
    btnH = Screen.width * 0.1;
    }

    function startServer()
    {
    Network.InitializeServer(32, 34061, !Network.HavePublicAddress);
    MasterServer.RegisterHost(gameName, “Network Testing Game”, “This is a game to test Networking”);
    }

    function refreshHostList()
    {
    MasterServer.RequestHostList(gameName);
    refreshing = true;
    }

    function Update ()
    {
    if( refreshing )
    {
    if(MasterServer.PollHostList().Lenght > 0)
    {
    refreshing = false;
    Debug.Log(MasterServer.PollHostList().Lenght);
    }
    }
    }

    //Messeges
    function OnServerInitialized()
    {
    Debug.Log(“Server initialized”);
    }

    function OnMasterServerEvent(mse:MasterServerEvent)
    {
    if(mse == MasterServerEvent.RegistrationSucceeded)
    {
    Debug.Log(“Server registered”);
    }
    }

    //GUI
    function OnGUI()
    {
    if(GUI.Button(Rect(btnX, btnY, btnW, btnH), “Start Server”))
    {
    Debug.Log(“Starting Server”);
    startServer();
    }
    if(GUI.Button(Rect(btnX, btnY * 1.2 + btnH, btnW, btnH), “Refresh Hosts”))
    {
    Debug.Log(“Refreshing”);
    refreshHostList();
    }
    }
    I cant seem to make it work .If you have any ideas on why this isn’t working please tell me.
    Thank you in advance

    • Posts: 109

      Hi Jimatos,

      On lines 35 and 38 you seem to have misspelled “Length” as “Lenght”. Though I find it weird this doesn’t give you a compile-time error (i.e.: one that prevents you from clicking Play), this is the only thing I can find wrong with it, and it seems to work fine here. =)

      Cheers,
      Patrick

  48. Posts: 1
    John says:

    This is amazing (have´nt tried it out myself yet but based on what i see it´s truly amazing. I don´t get it thou, does unity provide with servers for any developer who wants one? How many players could i ahve connected at once, would 5-10 be possible? I´m thinking of making sort of a 2.5D tanks game.

  49. Posts: 2
    Tropicaya says:

    Thank you, Patrick. That was awesome. It cleared up a lot of confusion, especially about “who is who”.

  50. Posts: 1
    Roger0 says:

    How would I sync a character animation over a network?

    • Posts: 2
      Tropicaya says:

      I think they said to use another networkView component for the Animation Component. I haven’t tried any of this myself. Still new to this.

  51. Posts: 1
    i eat pixels says:

    This video was great and I’m now a paid member! I’m trying to create a game which uses first person. Do you have any plans make a first person network tutorial Patrick?

    Thanks

    Paul

  52. Posts: 1
    nekonya says:

    Nice tutorial :)
    I got one problem, the character movement on the client side is stuttering when I move it from the server side.
    How do I fix this?

  53. Posts: 1
    Ryba says:

    Tutorial is fine, but i dont understand why there is this strange fashion for creating video tutorials. Its nightmare to search anything particular in 40 minutes video :( Why dont you make text tutorials ?

  54. Posts: 3
    Romano says:

    Great tutorial but I have 1 problem. I have 2 cubes, both with the 3rd person controller attached and both have a camera as a child. But the camera follows the wrong cube. The camera attached to cube 1/ the camera on screen 1 stays still unless I move it in the second screen. How can I solve this problem? Ask me if you need the scripts.

    • Posts: 3
      Romano says:

      Okay, I fixed it, people on the Unity forums helped me.

  55. Posts: 1
    bradmarxmoosepi says:

    This tutorial is excellent. Thank you!

  56. Posts: 1
    Bennet says:

    I’m getting a weird bug. I have no error messages but when I spawn a character I can move it around but when I spawn another character the computer that’s started the server takes control of the newly spawned character. I assume I’m just missing a symbol somewhere but I’m not really sure where.

    Thanks for the help,
    Bennet

  57. Posts: 2
    justindacosta says:

    I am having trouble getting the server to start. the debug just satys on starting server forever.

    • Posts: 2
      justindacosta says:

      I fixed this but now when I am testing the multiplayer feature with a test build I cannot get onto a started server with another computer Bering an error saying that it cannot connect because of the device being connected already. Does anyone know what is going on?

  58. Posts: 3
    Romano says:

    I can make a server and enter it when I have 2 instances of the game running on my computer. But when I send an instance of the game to my friend, it only displays the server on the GUI button, but he can’t join it. How can I solve this problem. Here’s my script:

    var gameName : String = “Arandomgamename”;
    private var refreshing : boolean;
    private var hostData : HostData[];
    var player : GameObject;
    private var btnX : float;
    private var btnY : float;
    private var btnW : float;
    private var btnH : float;
    var myCam : Camera;
    var myAudioListener : AudioListener;

    function Start () {
    btnX = Screen.width * 0.05;
    btnY = Screen.width * 0.05;
    btnW = Screen.width * 0.1;
    btnH = Screen.width * 0.1;
    }

    function StartServer () {
    Network.InitializeServer(32,25001, !Network.HavePublicAddress);
    MasterServer.RegisterHost(gameName, “Random Name”, “Derp”);
    }

    function RefreshHostList (){
    MasterServer.RequestHostList(gameName);
    refreshing = true;
    }

    function Update (){
    if (refreshing){
    if (MasterServer.PollHostList().length > 0){
    refreshing = false;
    Debug.Log(MasterServer.PollHostList().length);
    hostData = MasterServer.PollHostList();
    }
    }
    }

    function SpawnPlayer () {
    var playerInstance : GameObject = Network.Instantiate(player, gameObject.transform.position, gameObject.transform.rotation, 0);
    myCam = playerInstance.GetComponentInChildren(Camera);
    myAudioListener = playerInstance.GetComponentInChildren(AudioListener);
    if (playerInstance.networkView.isMine){
    if (myCam.enabled == false){
    myCam.enabled = true;
    }
    if (myAudioListener.enabled == false){
    myAudioListener.enabled = true;
    }
    }
    }

    // Messages
    function OnServerInitialized () {
    Debug.Log(“Server Initialized”);
    SpawnPlayer ();
    }

    function OnConnectedToServer () {
    SpawnPlayer ();
    }

    function OnMasterServerEvent(mse : MasterServerEvent){
    if (mse == MasterServerEvent.RegistrationSucceeded){
    Debug.Log(“Registered Server”);
    }
    }

    // GUI
    function OnGUI () {
    if (!Network.isClient && !Network.isServer) {
    if (GUI.Button(Rect(btnX, btnY, btnW, btnH), “Start Server”)){
    Debug.Log(“Server Starting”);
    StartServer ();
    }
    if (GUI.Button(Rect(btnX, btnY * 1.2 + btnH, btnW, btnH), “Refresh Hosts”)){
    Debug.Log(“Refreshing”);
    RefreshHostList ();
    }
    if (hostData){
    for (var i : int = 0; i < hostData.length; i++){
    if (GUI.Button(Rect(btnX * 1.5 + btnW, btnY * 1.2 * (btnH * i), btnW * 3, btnH * 0.5), hostData[i].gameName)){
    Network.Connect(hostData[i]);
    Debug.Log("herp");
    }
    }
    }
    }
    }

    Have I made a typo or did I do something else wrong?

  59. Posts: 2
    eoghan says:

    Hi
    Great tutorial.
    One problem I have i hope you can help me out with is I cannot seem to get my server registered.

    I wonder if I could send you my code, because I just cannot figure out where im going wrong. I have followed every step of your tutorial.

    Thanks in advance.

  60. Posts: 2
    eoghan says:

    // Network manager script

    var gameName:String = “EoghanNetworking”;

    private var refreshing:boolean;
    private var hostData:HostData[];
    var btnX:float;
    var btnY:float;
    var btnW:float;
    var btnH:float;

    function Start(){
    btnX = Screen.width * 0.05;
    btnY = Screen.width * 0.05;
    btnW = Screen.width * 0.1;
    btnH = Screen.width * 0.1;
    }

    function startServer(){
    Debug.Log(“before line 21″);
    Network.InitializeServer(32, 25015, !Network.HavePublicAddress);
    MasterServer.RegisterHost(gameName, “Tutorial GameName”, “this is a tutorial game”);
    Debug.Log(“Server is connected”);
    }

    function refreshHostList(){
    MasterServer.RequestHostList(gameName);
    //yield WaitForSeconds(1.5);
    //Debug.Log(MasterServer.PollHostList().Length);
    refreshing = true;

    }

    function Update(){
    if(refreshing){
    if(MasterServer.PollHostList().Length > 0){
    refreshing = false;
    Debug.Log(MasterServer.PollHostList().Length);
    hostData = MasterServer.PollHostList();
    }
    }
    }

    //messages
    function OnServerInitialised(){
    Debug.Log(“Server Initialised! “);
    }

    //Debug.Log(“before registration”);
    function OnMasterServerEvent(msEvent: MasterServerEvent) {
    if (msEvent == MasterServerEvent.RegistrationSucceeded) {
    Debug.Log(“Registered Server”);

    }

    }

    //if (OnMasterServerEvent != MasterServerEvent.RegistrationSucceeded){
    //Debug.Log(“msEventfailed”);
    //}

    //GUI
    function OnGUI () {
    if (GUI.Button (Rect (btnX,btnY,btnW,btnH), “Start Server”))
    Debug.Log(“starting server”);
    startServer();
    //OnMasterServerEvent(msEvent: MasterServerEvent);
    //Network.InitializeServer(32, 29978, !Network.HavePublicAddress);
    //MasterServer.RegisterHost(gameName, “Tutorial GameName”, “this is a tutorial game”);
    //Debug.Log(“Server is connected”);
    //OnServerInitialised();

    if(GUI.Button(Rect(btnX, btnY * 1.2 + btnH, btnW, btnH), “refresh hosts”)){
    Debug.Log(“refreshing”);
    refreshHostList();
    }

    if(hostData){
    for(var i:int = 0; i<hostData.length; i++){
    GUI.Button(Rect(btnX * 1.5 + btnW, btnY*1.2 + (btnH * i), btnW*3, btnH*0.5), hostData[i].gameName);
    Debug.Log("button 3 display");
    }
    }
    }

  61. Posts: 1
    jib says:

    Hello when i try to put my camera follows my cube i’ve got this error[i copied the script from a comment]
    :

    The best overload for the method
    ‘UnityEngine.Network.Instantiate(UnityEngine.Object, UnityEngine.Vector3, UnityEngine.Quaternion, int)’ is not compatible with the argument list ‘(UnityEngine.GameObject, int, int, int)’.

  62. Posts: 1

    Hey – thank you for this tutorial!
    I get this error message:

    View ID SceneID: 1 Level Prefix: 0 not found during lookup.

    Received state update for view id’ SceneID: 1 Level Prefix: 0′ but the NetworkView doesn’t exist

    My Network script doesn’t get any errors though.
    How can I fix it? What is the problem with my setup?

  63. Posts: 1
    drytear says:

    Does this game works with online global ip (wimi.com) or does it only work with LAN and Hamachi

  64. Posts: 1
    kylan says:

    I have a question on networking. I followed this example and made a PC client that worked between computers on my LAN. Then I ported the example to an Android app. I wanted to play between the PC client and the android app but they don’t seem to see each other. If I play the android app on the Unity IDE and start the server there I can connect my android app on the phone to the server but I cannot figure out why the PC client doesn’t want to work with the android client. I am using the exact same NetworkManagerScript for both.

  65. Posts: 1
    Murilo says:

    Hello , and thx for the awesome tutorial, but when I refresh the server lists , it tells me that hostData is null, and I kept trying to fix but couldnt reach a answer, maybe you can help?

  66. Posts: 1

    I really found your tutorial very good to get up and running with unity basic networking, along with simple RPC..

    I was looking for more but couldn’t find anything on networking through the site.

    Are you planning on doing any more tutorials like this one?

    I’m trying to work out how to do the collision detection based on a ray-cast hit. I’m told in order to do that correctly I have to make an authoritative server, to calculate the players position based on the ray hit, location. But that seems like over kill at the moment.

    I can see you running around over there but I cant hit you, as I have to go and build a much more complex system… Seems very odd to me.. lol.

  67. Posts: 1

    Hey, great tut and thanks for leading me on a direction which I knew nothing about. :)

    But I am having one error in my script when I made it, it doesn’t either connect to the server it creates, or it doesn’t creates the server. Could you help me fix this? thanks.

    I’ll leave it here if you got time to help. Thanks again.
    #pragma strict
    var playerPrefab: GameObject;
    var spawnPoint: Transform;
    var gameName: String;

    private var refreshing: boolean;
    private var hostData: HostData[];

    function Start () {
    gameName = “This_Pirate_Game_Rocks_12″;
    }

    function Update () {
    if (!Network.isClient) {
    refreshHostList();
    Debug.Log(“Refreshing List”);
    if (refreshing) {
    hostData = MasterServer.PollHostList();
    Debug.Log(“Getting hostData”);
    if (hostData) {
    if (hostData.Length <= 0) {
    Debug.Log("No sever found. Starting sever.");
    startServer();
    Debug.Log(hostData.Length);
    }
    else {
    Network.Connect(hostData[0]);
    Debug.Log("You're connect to the server!");
    refreshing = false;
    }
    }
    }
    }

    }

    function spawnPlayer() {
    Network.Instantiate(playerPrefab, spawnPoint.position, Quaternion.identity, 0);
    }

    function startServer() {
    Network.InitializeServer(32,25001, !Network.HavePublicAddress);
    MasterServer.RegisterHost(gameName, "Wonderful Pirate Game", "HI");
    Debug.Log("Created server!");
    }

    function refreshHostList() {
    MasterServer.RequestHostList(gameName);
    refreshing = true;
    }

    function OnConnectedToServer() {
    spawnPlayer();
    }

  68. Posts: 1

    hey, great tutorial, i was wondereing how would you make it a random spawn point. I have been searching the internet all over with no succes. please help anyone!!!

    • Posts: 158
      Metalix says:

      You will need to create an array from all objects with the tag spawn point, then use the rand(0,10) function to select a spawn point to use in your spawn script. Gabriel teaches spawning in the tower defense series.
      -Alex

  69. Posts: 1
    Mertcan Çezik says:

    Man this is really helpful for the people who know how to code well. You check everything in update and that update thing gives game a cancer!!. You should use more events. But thanks it is really helpful!!

  70. Posts: 1
    caesar says:

    For the first time as a hobbiest game developer over the course of 20+ years, I was able to not only follow along perfectly, but was able to create a fully functioning networking example. I’ve gone through just about every tutorial there is on the subject and Mr. Boelens has nailed it. Thank you sir.

  71. Posts: 1
    Parasigma says:

    “Failed to conect to master server”

    Te registration of the master server doesnt work :S

  72. Posts: 1
    tumitoto says:

    Thank you for the great intro tutorial!!

  73. Posts: 1
    Rytis Buzys says:

    Hey, great tutorial!
    But I have a problem. I’ve done everything exactly like in your video untill 30:20~ And there you’re moving your cube only in your server window. It worked for me as well, but when I tried to move it in client’s window the cube moved only in client’s window. Is it should be like this? Or there is something wrong? I actually need in my project, that both client and server could controll same object.

    P.S. I’m not sure but earlier I did the same and it worked for me, could it be my network problem, or something else?

    • Posts: 158
      Metalix says:

      Looks like your script is not updating from the client, post your script onto the forums and we can take a look.
      -Alex

  74. Posts: 1
    Tong says:

    Download link is invalid? is it my problem? anyone able to download the files?

    • Posts: 158
      Metalix says:

      Works fine for me, I believe the source files are just for citizens.
      -Alex

  75. Posts: 1
    vlad vod says:

    Very good tutorial, thank you. It was pretty fast introduction to networking. Will there be next part? I think, that a lot of people is interested in smoothing network movement and also physics over network. The last mentioned is poorly documented, there is no good tutorial for this on whole Internet! Are you interested in making one? :)

  76. Posts: 2
    Elis says:

    Hey! Great tutorial! I tried to make this on my mac wich is using unity 3 and now I tried again on my normal pc wich have unity 4 and I still get that error you got before you added in if(hostData) at 23:50, I’ve added in the if(hostData) but when I refresh and it’s done refreshing the error pops up! I dont know what’s wrong! help?

    • Posts: 2
      Elis says:

      Edit: It worked on my mac!

  77. Posts: 1
    Crunch says:

    Great tutorial and teacher. Can we expect more advanced networking tutorials? Perhaps applying it to different genres (FPS, RTS, ect.)?

  78. Posts: 2
    Alper says:

    Hey all,

    First thanks for the great tutorial. Have a question. Can I join a server if my device in a different network? For ex. me at work and my friend is at home. Can I join his game ?

    Asked that question cause when I try to join game, I can’t.

    • Posts: 2
      Alper says:

      — aditional information —

      I can see the games created on the server but I get that message

      ” Are you sure the server can be connected to? “

  79. Posts: 1

    Great tutorial :) however I getting this error:

    Failed to connect to master server at 67.225.180.24:23466

    any help would be very much appreciated

    Thanks

  80. Posts: 1
    keleopatra says:

    hi my brother
    i can not speek english so excuse me if write bad.
    i see and used your code but when run it ,game cant register.why?
    my system have not valid ip too.

  81. Posts: 1
    Poul Carlsen says:

    love the Tutorial, all works fine
    Just what i was looking for, thank you

  82. Posts: 1

    Thanks For the great tutorial, but i still got this weird thing. When i play with one player everything works just fine, but when i connect with another player, we are controlling each others characters.

    i use “if (networkView.isMine)” in the update function of my playercontroller.

    http://pastebin.com/20iDxUXk

    here is my source code in c#

  83. Posts: 1
    luke stonier says:

    Hello. Great Tutorial but how would i get my friend from school to connect from where he lives? thanks -luke stonier

  84. Posts: 1
    Logan Scott says:

    Hey, I have this REALLY weird problem where the networkView.isMine seems to do the opposite of what its so post to do. I can control the other character than mine in the game. I have NO idea how this could happen and I’d like some help fixing this problem.

  85. Posts: 1

    Great Tutorial!! Is it possible to use this interface on other programs? In my case I want to control the transform of a hand from inside Matlab, could you give me some pointers as to where to start looking? Thanks :)

  86. Posts: 2

    I don’t have the Movement script i have searched for with no success could u please put a copy of it on a reply to this here is what I tried to copy from your but i got 7 errors.script

    var speed:inty = 5;
    var gravity = 5;
    private var cc:CharacterController;

    function Start(){
    cc = GetComponent(CharacterController);
    }

    function Update(){
    if(netowrkView.isMine){
    cc.Move(Vector3(.Input.GetAxis(“Horizontal”) * speed * Time.deltaTime, -gravity * Time.deltaTime, Input.GetAxis(“Vertical”);
    }
    }

  87. Posts: 1
    Opsed Akilon says:

    Many thanks for the tutorial.

    Helped me a lot! Just like to warn you that there is an error. Missing parentheses at the end of the function !Network.HavePublicAddress(). Without them the code only works locally.

  88. Posts: 1
    pixelboi says:

    @Patrick I just checked out the tutorial and it is fantastic. I do have a question for you and maybe you can help me with it. The scene I used this tutorial on is a 2D platformed scene. I’m using the Unity 2D scene. The issue I have is with the camera. Nesting the camera in the character prefab has some undesired results when you go left to right. How else can I have it so each player that joins a game has their own camera, but not parented to the player? Thanks. I can inbox you the camera script if you need it. Thanks for any help!

Leave a Comment

You must be logged in to post a comment.