Search Unity

  1. We're looking for feedback on Unity Starter Kits! Let us know what you’d like.
    Dismiss Notice
  2. Unity 2017.2 beta is now available for download.
    Dismiss Notice
  3. Unity 2017.1 is now released.
    Dismiss Notice
  4. Introducing the Unity Essentials Packs! Find out more.
    Dismiss Notice
  5. Check out all the fixes for 5.6 on the patch releases page.
    Dismiss Notice
  6. Help us improve the editor usability and artist workflows. Join our discussion to provide your feedback.
    Dismiss Notice

Unity 5 UNET Multiplayer Tutorials - Making a basic survival co-op

Discussion in 'Community Learning & Teaching' started by GTGD, May 13, 2015.

  1. Yash987654321

    Yash987654321

    Joined:
    Oct 22, 2014
    Posts:
    730
    Thanks for sharing :) But can you make a torrent and upload. I want to learn but because of slow internet I cannot see online videos :(
     
    dsh likes this.
  2. jathrek

    jathrek

    Joined:
    Jul 16, 2015
    Posts:
    36
    Hello,

    First, thank you for sharing these videos (I found about them some time ago on Reddit, but was only able to start watching them today)!

    I started playing with Unity only recently (v. 5.0), and it seems I was lucky to join just when a new networking engine comes out and someone starts marking nice & practicacl network tutorials. ;-)

    I would have a few questions (well, one for now), though...
    (I just hope that they've not been answered in later videos as I only watched the few first ones for now.)

    But, first, a personal point of view of mine, concerning the NetworkTransform interpolation (which has probably been already confirmed/rejected, but who knows - surely not me ;-p);
    I think the interpolation only works when synching the RigidBody, in which case it is based on the forces applied to the rigidbody and not the direct changes to the rotation/position.
    Let's say you have a player-controller spaceship that is move using only forces (push "up" arrows will add some force going forward), then you could have a network synch only every 1/10th of seconds (probably not enough for a nice feel, but sufficient to explain my point of view), but each client could interpolate in-between positions by applying the last known force to the others' spaceships every frame, thus with a correction on network synch.
    Seems plausible?
    If yes, then it means that any game based on direct modification of the position/rotation would not be able to benefit from interpolation and would have to depend on either no interpolation at all, or mechanism similar to the lerping you've used in your first videos.

    Next, for the question, I'm wondering where/when is the FixedUpdate called (by the server? by the clients?)...
    My lack of experience makes it unclear for me, so based on your 1st and 2nd video, I'm wondering what is the actual "flow" in all the function calls;

    1. Does the server triggers the ClientCallback functions (that, in turn, call the Command functions to transmit the position/rotations) when the "FixedUpdate" is run?
    2. I suppose the "FixedUpdate" is also run on the clients?

    But, if both answers to 1 and 2 is "Yes", would it not be enough to just have the FixedUpdate call the "CmdTransmit~something~" functions for objects where isLocalPlayer equals to true?
    Because otherwise, I've the feeling that, at the same time, the server is polling all clients to send them their position/rotations, but the clients also send their position/rotations when the "FixedUpdate" function is called at their level.

    Hopefully, I've not said anything too stupid and you'll be able to help my novice brain. ;-)
     
  3. RavenLiquid

    RavenLiquid

    Joined:
    May 5, 2015
    Posts:
    19
    Your questions regarding FixedUpdate are answered in the 4th video (for the most part).

    For question 2, FixedUpdate is part of the MonoBehavior (and NetworkBehavior derives from this), so yes it is called on the clients as well because it is a game object with a MonoBehavior.

    As to when it is called, this is explained in video 4 but it is at fixed intervals (hence the Fixed part in the name). Update is called each frame

    More info on this learning page.
     
  4. jathrek

    jathrek

    Joined:
    Jul 16, 2015
    Posts:
    36
    Hello,

    My usually too-verbose questions and the fact that English is not my mother language might have made my question difficult to understand (or, rather, the written question is not reflecting what I had in mind ;-p). But I'll first check the 4th video before eventually going back to it.

    Sadly, I encountered another issue that prevent me from going further. I attempted to use the same "offline" and "online" scene approach, with the offline scene containing the network manager (and its HUD) and the online scene containing several prefabs added manually in the hierarchy and some scripts instantiating other prefabs as time goes.

    The main issue is that, although it worked when the network manager was in the online scene (and did not manage scene change), the player prefab does not get spawned anymore when the client switches from the offline to the online scene, after using the "LAN host" option (The prefab is setup - apparently - correctly in the Network manager, does have a network identity and a network transform). The game object does not even appear in the editor's hierarchy.

    The second issue, that might be related to the 1st one, is the fact that the prefabs that were present in the hierarchy directly (as they were manually added in the editor before running the project) get disabled as soon as the online scene is loaded. The prefabs spawned by script appears normally over time.

    I've been trying to figure something out of the logs, but nothing seems to be out of the ordinary (there's even a message indicating that the player prefab was registered as an asset, meaning that it probably is correctly set in the network manager)

    Any tips?

    [EDIT & SOLUTION]
    Well, I found it by chance and, although it's quite logic (and probably plain stupid for people with a lot of Unity experience), I'll try to save my honor that it's a bit twisted as well ;-p. Both the offline and the online scenes contained an empty GameObject used for organization called "Managers", used to regroup the "singleton" GameObjects of my game. It seems like that, when the scene change occurs, the "Managers" of the online scene fully overwrite the content of the "Managers" from the offline scene (instead of merging them), removing any child GameObject that were already present, including the network manager which is thus not able to finish his work (spawn the player prefabs, handle the existing objects...).


    Thank you.
     
    Last edited: Jul 23, 2015
  5. GreekStudios0

    GreekStudios0

    Joined:
    Jul 7, 2014
    Posts:
    321
    Hey, thanks for your great tutorial.

    I would like to ask something.

    Assume that i made my game and works perfect on local host, what should i do to make a server on the internet and play or how to actually allow users to host their match and allow others to join.

    I hope you understood what i said :p.
     
  6. webagency1

    webagency1

    Joined:
    Jun 13, 2015
    Posts:
    9
  7. GTGD

    GTGD

    Joined:
    Feb 7, 2012
    Posts:
    420
    Matchmaking is what you're trying to do. One of my later videos shows that but in my case I was unsuccessful in maintaining a connection because I had too many zombies firing off too much data across the network.

    Now you can use hamachi or port forwarding if you know what you're doing. Video 20 talks about that briefly. For a truly public game yes you need to use matchmaking so that players can see a list of public servers and easily select which one they want to join.
     
  8. webagency1

    webagency1

    Joined:
    Jun 13, 2015
    Posts:
    9
    Thank you. I want to connect through Unity multiplayer server. Do I still need matchmaking? If so can you advice tutorial how to make matchmaking? Nether your, not Unity's Network Lobby example do not work.. I am doing everything as described ...
     
  9. GTGD

    GTGD

    Joined:
    Feb 7, 2012
    Posts:
    420
    Video 19. No I haven't looked into the Network Lobby yet.
     
    webagency1 likes this.
  10. webagency1

    webagency1

    Joined:
    Jun 13, 2015
    Posts:
    9
    thanks! Will try
     
  11. bigbrainz

    bigbrainz

    Joined:
    Jul 21, 2015
    Posts:
    54
    LOVE this tutorial--thank you!! Could you by chance expound a bit more on matchmaking Tutorial #19? I've created a multiplayer project and plugged in the Cloud Project ID to the appropriate spot, but it still gives me an error. As nearly as I can tell, I still need to reference the 6-digit "UNET ID" listed below the forever long "Cloud Project ID". I just can't sort out exactly how or where to plug that in . . . ? I'm not sure if something changed in the official release of 5.1, but here are some of the error snippets I'm getting:

    "Failed to read the ID for the match maker . . . "
    ". . . Failed CreateMatch for appId = Invalid]"
    If you could enlighten me I would greatly appreciate it!

    Best wishes
     
  12. GTGD

    GTGD

    Joined:
    Feb 7, 2012
    Posts:
    420
    When I create a new cloud project id I have to wait a few minutes before I can use it. Apart from that it is just pasting the id into the player settings like I did in the video.
     
  13. Xazerek

    Xazerek

    Joined:
    Nov 3, 2014
    Posts:
    134
    @GTGD
    Hi! What is wrong in my srcipt?

    Code (csharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using UnityEngine.Networking;
    4.  
    5. public class Player_SyncPosition : NetworkBehaviour {
    6.  
    7.     [SyncVar]
    8.     private Vector3 syncPos;
    9.  
    10.     [SerializeField] Transform myTransform;
    11.     [SerializeField] float lerpRate = 15;
    12.  
    13.  
    14.         // Update is called once per frame
    15.         void FixedUpdate ()
    16.         {
    17.             TransmitPosition();
    18.             LerpPosition();
    19.         }
    20.      
    21.         void LerpPosition ()
    22.         {
    23.             if(!IsLocalPlayer)
    24.             {
    25.             myTransform.position = Vector3.Lerp(myTransform.position, syncPos, Time.deltaTime * lerpRate);
    26.             }
    27.         }
    28.      
    29.         [Command]
    30.         void CmdProvidePositionToServer (Vector3 pos)
    31.         {
    32.             syncPos = pos;
    33.         }
    34.      
    35.         [ClientCallback]
    36.         void TransmitPosition()
    37.         {
    38.             CmdProvidePositionToServer(MyTransform.position);
    39.         }
    40. }
    41.  
    42.  
    Errors:
    Code (csharp):
    1.  
    2. Assets/Scripts/Player_SyncPosition.cs(23,29): error CS0103: The name `IsLocalPlayer' does not exist in the current context
    3.  
    Code (csharp):
    1.  
    2. Assets/Scripts/Player_SyncPosition.cs(38,52): error CS0103: The name `MyTransform' does not exist in the current context
    3.  
    Code (csharp):
    1.  
    2. Assets/Scripts/Player_SyncPosition.cs(38,25): error CS1502: The best overloaded method match for `Player_SyncPosition.CmdProvidePositionToServer(UnityEngine.Vector3)' has some invalid arguments
    3.  
    Code (csharp):
    1.  
    2. Assets/Scripts/Player_SyncPosition.cs(38,25): error CS1503: Argument `#1' cannot convert `object' expression to type `UnityEngine.Vector3'
    3.  
    Thanks in advance, this tutorial is awesome!

    EDIT: Btw. is it only for LAN? Cause i can't connect with different computers.
     
    Last edited: Aug 3, 2015
  14. Pnshr38

    Pnshr38

    Joined:
    Feb 4, 2015
    Posts:
    2
    Thanks bro this is awesome
     
  15. RavenLiquid

    RavenLiquid

    Joined:
    May 5, 2015
    Posts:
    19
    I'm not sure about MonoDevelop (as I use Visual Studio) but try to use code completion on these things, I think it should fix the capitals if the rest is spelled correctly.

    By the way, I'm not a fan of the myTransform anyway. It seems redundant as the script can already access transform directly.
     
  16. GTGD

    GTGD

    Joined:
    Feb 7, 2012
    Posts:
    420
    Hello, you've got your case wrong on the places shown in the errors. When coding make sure your case is correct. For example if the variable is myTransform it must be written as myTransform not MyTransform.
     
  17. Xazerek

    Xazerek

    Joined:
    Nov 3, 2014
    Posts:
    134
    @GTGD
    Thanks! :)

    Is it only LAN or it can work as online multplayer game?
    Cause i want to make multiplayer rpg game.
     
  18. GTGD

    GTGD

    Joined:
    Feb 7, 2012
    Posts:
    420
    Go study the Unity documentation for networking. You can do LAN or public games
     
  19. Xazerek

    Xazerek

    Joined:
    Nov 3, 2014
    Posts:
    134
    @GTGD Ok i got it.

    Will u make more tutorial about unet networking?
    Something like how to make chat for game etc?
     
  20. GTGD

    GTGD

    Joined:
    Feb 7, 2012
    Posts:
    420
    I'm intending to show how to implement a chat system. At the moment I'm a bit distracted by a game I'm working on called Weekend Drive. When I take a break from that I'll come back and make the tut.
     
  21. Xazerek

    Xazerek

    Joined:
    Nov 3, 2014
    Posts:
    134
    Hmm. On my PC i can make Internet match, and join. But my friends can't make internet match, and they are can't join.
    Do someone know how to fix it?
     
  22. Stoopers

    Stoopers

    Joined:
    Feb 25, 2015
    Posts:
    17
    i following this tutorial, and work good,..
    i host a server on Linux VPS with Headless Unity (Host Server)
    and open the game for public,.

    all running normally, until some player exit and entry server and a few minutes later a new player can not spawn,
    they already connect, but it stuck, player GameObject not spawning.

    note:
    I use the images "Connecting ..." as a GameObject and Destroy it when players spawn, .. but the player not spawning.

    then i duplicate the Game Process to fix this issue, but sometime it's not working too...


    this is a video to explain that all :


    i need a help please :'(
    thx before :D
     
  23. lucasbs1991

    lucasbs1991

    Joined:
    Jun 15, 2015
    Posts:
    4
    Same problem here, just my pc can create matchs, none of my friend can make or join :(
     
  24. Stoopers

    Stoopers

    Joined:
    Feb 25, 2015
    Posts:
    17
  25. bioert

    bioert

    Joined:
    Nov 9, 2014
    Posts:
    8
    Hello all. I have a problem with data persistence using the Network_Manager or other GameObjects. I'm trying to implement a save and load data system. What I'm trying to do is that when the player want to play, he input a name for the game, then start the local host. If I use the network_manager or other singleton to store this string it passes to the Online scene but when player returns to the main menu all is lost. Not only the value of the string but the references to, so I use the function OnLevelWasLoaded to re-establish references again. After you return to the main menu and try start a new game and assign a new name it does not persist to the online menu. What I suspect is that this new network manager is not loading the scenes like before and breaks the singleton functionality. Do anyone relate to this experience?
     
  26. GTGD

    GTGD

    Joined:
    Feb 7, 2012
    Posts:
    420
    Have you tried Unity 5.1.1p4 or a newer version?
     
  27. Stoopers

    Stoopers

    Joined:
    Feb 25, 2015
    Posts:
    17
    im using unity 5.1.2f1
     
  28. Superstition

    Superstition

    Joined:
    May 22, 2015
    Posts:
    3
    Have you looked into NetworkAnimator anymore?
    I built myself a prefab with a blendtree covering the directions, based on simple speed, turn, and strafe inputs. But the animator on any of the other clients is jittery. It is most noticeable in the transitions.
     
  29. Fr0stbite

    Fr0stbite

    Joined:
    Dec 18, 2012
    Posts:
    23
    Is it possible to use Unet with js?
     
  30. Senatauro

    Senatauro

    Joined:
    Feb 12, 2014
    Posts:
    3
    Yep, I made it entirely with JavaScript(UnityScript). The major problem that you may have will be translating it.
     
  31. GTGD

    GTGD

    Joined:
    Feb 7, 2012
    Posts:
    420
    I don't know if the animations are interpolated using the Network Animator component, it's possible they aren't and that's why it looks jittery. You can interpolate the values that drive the animation in a similar way to how I was interpolating the position and rotation, of course this means you won't be using the NetworkAnimator anymore and you'll be using your own code to sync the animation across the network. I did that in S2 for the old networking system and it worked well. If your blend tree is just for FPS character motion then I do recommend using 2D freeform cartesian, and horizontal and vertical axes as inputs, and that works very well and is easy to manually sync.
     
  32. GTGD

    GTGD

    Joined:
    Feb 7, 2012
    Posts:
    420
    At some point I'll download a newer version of Unity and see if I'm getting the problem you guys are getting. I'm using an older patch version 5.1.1p4 and the project is ok for me.
     
  33. Kiwiownage

    Kiwiownage

    Joined:
    Mar 26, 2014
    Posts:
    1
    Any chance you could make a tutorial on how to spawn different player prefabs?

    eg at the main menu you select your character and then it loads in through the network manager etc. (currently I can get mine to change player prefabs... but the client will ALWAYS spawn the hosts prefab regardless of which prefab i select) I'm guessing its a syncing issue? but I can't call clientRpcs or commands in a script that extends NetworkManager.

    Code (csharp):
    1.  
    2. public override void OnServerAddPlayer (NetworkConnection conn, short playerControllerId)
    3.     {
    4.         if (heroSelect == wizardPrefab) {
    5.             GameObject player = (GameObject)GameObject.Instantiate (wizardPrefab, heroSelect.transform.position, Quaternion.identity);
    6.             NetworkServer.AddPlayerForConnection (conn, player, playerControllerId);
    7.             Debug.Log ("Wziard");
    8.         }
    9.         if (heroSelect == warriorPerfab) {
    10.             GameObject player = (GameObject)GameObject.Instantiate (warriorPerfab, heroSelect.transform.position, Quaternion.identity);
    11.             NetworkServer.AddPlayerForConnection (conn, player, playerControllerId);
    12.         }
    13.         if (heroSelect == roguePrefab) {
    14.             GameObject player = (GameObject)GameObject.Instantiate (roguePrefab, heroSelect.transform.position, Quaternion.identity);
    15.             NetworkServer.AddPlayerForConnection (conn, player, playerControllerId);
    16.         }
    17.     }
    18.  
    19.  
     
    lucasbs1991 and Xazerek like this.
  34. GTGD

    GTGD

    Joined:
    Feb 7, 2012
    Posts:
    420
    I haven't actually put any though into that. I could make one suggestion. Perhaps you could place multiple character types under the one player prefab and then just activate the one that the player chose?
     
    Xazerek likes this.
  35. GTGD

    GTGD

    Joined:
    Feb 7, 2012
    Posts:
    420
    I'm using Unity 5.1.2p3 now and everything seems to be working.
     
  36. madelinot

    madelinot

    Joined:
    Jul 15, 2015
    Posts:
    5
    Hi ! I'm stuck on 3 problems , i dont know where i got it.

    1: I spawn always my first player as Player 2 id. (and i see in your video your spawn as Player 1)
    I see at some time, if i connect some new player late in the game , they can be Player 124 player 256 etc...



    2: Each time i disconnect (I go to lobby) i got warning :
    Multiple NetworkManagers detected in the scene. Only one NetworkManager can exist at a time. The duplicate NetworkManager will not be used.
    UnityEngine.Networking.NetworkManager:Awake()

    i think the Check case on dontDestroyOnLoad into NetworkManager cause it


    3: Yesterday i tryed to spawn some more mobs with new names, new tag and new spawn ,set their ID and their target , respectively of each kind of mobs , all new mobs work very well but my old Zombies Spawn at a good position but never follow or attack me now , As far as i can remember ,2 day ago my zombies worked very wells. I didnt pay attention on my zombie if they could attack me or not on each new test, because they was working pretty well.


    My logic of the problem : Because my NetworkManager is Duplicated thats count as a new player with another name than "" or "Player(Clone)" and then my zombies try to find the invisible player in the Weird Space.

    But how can i resolve this
     
  37. bioert

    bioert

    Joined:
    Nov 9, 2014
    Posts:
    8
    Hello,

    I also stumble upon the Problem #2. I looked it up and found is related to an Unity Bug. Try not to use the NetworkManager as a "classic" singlenton, instead create a separate GameObject Game Manager and make it a singlenton.

    What I found is that you need to establish each relative references, variables, UI, each time you Enter the game for the first time, load the online scene and go back to the offline scene. Try using OnlevelLoad to "Re-establish" variables and references.
     
  38. madelinot

    madelinot

    Joined:
    Jul 15, 2015
    Posts:
    5
    Oh! thanks you very much bioert. I will try it. I'm busy at the moment for testing it but i will do it later.
     
  39. DinostabOMG

    DinostabOMG

    Joined:
    Jan 4, 2014
    Posts:
    5
    I've only got through the first tutorial so far, but I am curious why you make everything [SerializeField]?
     
  40. crackporta

    crackporta

    Joined:
    Nov 4, 2014
    Posts:
    1
    Amazing tutorial! Thanks man!
     
  41. madelinot

    madelinot

    Joined:
    Jul 15, 2015
    Posts:
    5
    but how to setup the networkID and transform then ? could you explain ??


    if i only make empty GameObject and put all of them into a parent. The new player Parent need networkID and how will work the transform after?
     
  42. GTGD

    GTGD

    Joined:
    Feb 7, 2012
    Posts:
    420
    The network scripts remain on the root gameobject. Underneath there are Player type A, B, C, etc. You only activate the one the player selected. Sync this selection across the network so that the correct player is enabled on remote instances. There's no need to change the networkID. If the player types are all the same size then positions of player items, such as weapons, can remain the same and independent of the player type game objects.
     
  43. NotQuiteSmith

    NotQuiteSmith

    Joined:
    Oct 27, 2013
    Posts:
    13
    Great tutorials - thanks!
    Has anyone tried taking more control of the matchmaking process e.g. take a list of players and match them based on custom criteria. I see the API has commands related to creation/joining of rooms but I'm confused about exactly how to do it. e.g. when does someone become the host - is it the first person you put in the room? Can I setup variables, etc in that initial host and have them propagate to other players as they join? Those kinds of things.

    Thanks for any help!
     
  44. GenaSG

    GenaSG

    Joined:
    Apr 19, 2014
    Posts:
    89
    Thank you a lot for your tutorials.
    Cheers
     
  45. sebeisdrache

    sebeisdrache

    Joined:
    Jan 16, 2015
    Posts:
    34
    Hello, I made my code mostly like your tutorial.

    But in Unity 5.2 i have big lags now. It was all fine in 5.1
     
    Last edited: Sep 11, 2015
  46. LeopardX

    LeopardX

    Joined:
    May 31, 2015
    Posts:
    61
    Hi @GTGD wonderful tutorials btw loved watching and learning from them, I however have a problem with the method you used to spawn the zombies, it dosent spawn properly over the network only on one direction like host to client but not from client to host, the error i get is:

    SpawnObject for Cube(Clone) (UnityEngine.GameObject), NetworkServer is not active. Cannot spawn objects without an active server.
    UnityEngine.Networking.NetworkServer:Spawn(GameObject)
    ClickToRez:Update() (at Assets/Scripts/ClickToRez.cs:28)

    So i looked on the internet and saw nothing about this error, but then looked at the networkserver spawn function, and saw that some had to do this function via a [Command] so i edited my code to do that, and it fixed the error, however when i pass a vector3 as one of the arguments i setup for the command function its always 0,0,0 not what i pass to it.

    However i was wondering why it works for you without using spawn under a server command, and mine dose not, any ideas ?

    Heres my spawn code:

    using UnityEngine;
    using System.Collections;
    using UnityEngine.Networking;

    public class ClickToRez : NetworkBehaviour {

    [SerializeField]
    GameObject rezObject;

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update()
    {

    if (isLocalPlayer) {
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    RaycastHit hit;

    if (Input.GetButtonDown("Fire2"))
    {
    if (Physics.Raycast(ray, out hit, 50f))
    {
    // GameObject go = GameObject.Instantiate(rezObject,hit.point,Quaternion.identity) as GameObject;
    // NetworkServer.Spawn(go);
    Cmdrezobjectonserver(rezObject, hit);
    }
    }
    }
    }

    [Command]

    void Cmdrezobjectonserver(GameObject Obj, RaycastHit hitx) {
    GameObject go = GameObject.Instantiate(rezObject, hitx.point, Quaternion.identity) as GameObject;
    NetworkServer.Spawn(go);
    }
    }
     
  47. LeopardX

    LeopardX

    Joined:
    May 31, 2015
    Posts:
    61
    I got this working fully now, but i had to use spawn under [Command].
     
  48. Useless-Media

    Useless-Media

    Joined:
    Apr 19, 2015
    Posts:
    44
    Hey, can some of you tell me how i got only the Animations working?
    I watched Part 21 - Network Animator because thats all i need to know.

    Maybe a small code example ore something where i can start from it.
    Thanks
     
  49. FuzzyShan

    FuzzyShan

    Joined:
    Jul 30, 2012
    Posts:
    121
    I am using Unity5.2.0 I get the same problem Stoopers is geting, which is that warning message stops player from spawning.
     
  50. 009

    009

    Joined:
    Nov 7, 2013
    Posts:
    12
    Hi Sir,
    Thanks for the great tutorial. I have going through the first episode it works fine at the PC. But there is problem when I try to build in the Android Phone. I just get a fancy fuzzy screen like the TV can't get the signal LOL, is that any other things to do for a mobile device?